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

问题描述 投票:1回答:3

使用对象,我可以将一个键包装在方括号中,如下所示:

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

有办法吗?

javascript arrays
3个回答
2
投票

点符号和方括号都是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]

0
投票

您可以使用相同的语法:

const category = 'foo'
const items = {foo: [1, 2, 3]}
const item = 4
    
console.log({ items: [...items[category], item] })

0
投票

如果要使用其他变量访问foo属性,可以使用方括号表示法,如下所示:

const category = 'foo'
const items = {
  foo: [1, 2, 3]
}

const item = 4

console.log( { items: [...items[category], item] });
© www.soinside.com 2019 - 2024. All rights reserved.