繁体   English   中英

有没有一种简单的方法可以通过字符串访问数组元素?

[英]Is there an easy way to access an array element via a string?

对于对象,我可以将键包裹在方括号中,如下所示:

// 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 

我希望能够在B.js中获得{items:[1、2、3、4]}

有办法吗?

点符号和方括号都是属性访问器

如果使用点符号,则该属性必须是实际的属性名称:

  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] });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM