有没有简单的方法通过字符串访问数组元素?
有了对象,我可以在方括号包裹的关键,像这样:有没有简单的方法通过字符串访问数组元素?
// A.js const category = 'foo' 
return { [category] : 'bar' } // { foo: 'bar' } 
有没有一种简单的方法做数组元素一样吗?像
// B.js const category = 'foo' 
const items.foo = [1, 2, 3] 
const item = 4 
return { items: [...items.category, item] } // throws an error 
我希望能够得到{项目:1,2,3,4]}在B.js
有没有办法?
回答:
两个点号和方括号property accessors。
如果使用点符号,属性必须是实际的属性名称:
words=new Object;      words.greeting='hello';  
    console.log(words.greeting);  //hello  
    console.log(words['greeting']); //hello  
    console.log(words[greeting]); //error
在第三个例子,greeting被视为一个变量,而不是作为一个字符串字面,并且因为greeting尚未定义为变量,所以JavaScript解释器会引发错误。
如果我们定义greeting作为一个变量:
var greeting = 'greeting'; 第三示例工作:
words=new Object;      words.greeting='hello';  
    var greeting='greeting';  
    console.log(words[greeting]);
因此,你需要用方括号属性访问:
[...items[category],item] 回答:
您可以使用相同的语法:
const category = 'foo'  const items = {foo: [1, 2, 3]}  
const item = 4  
console.log({ items: [...items[category], item] })
回答:
如果要使用另一个变量来访问foo属性,你可以用方括号符号,就像这样:
const category = 'foo' const items = { 
    foo: [1, 2, 3] 
} 
const item = 4 
console.log({ items: [...items[category], item] }); 
以上是 有没有简单的方法通过字符串访问数组元素? 的全部内容, 来源链接: utcz.com/qa/261996.html







