如何向数组中添加对象?具体如何给living Room的items数组添加'dining table'
如何将'dining table'添加到living Room的items数组中
要把'dining table'添加到你提供的house对象里living Room的items数组中,核心是先正确访问到这个数组,再用数组方法添加元素。因为living Room这个键名包含空格,不能用.点语法访问,必须用**方括号[]**来获取对应的属性。
方法一:用push()在数组末尾添加(最常用)
push()方法会把元素添加到数组的最后位置,代码如下:
let house = { areas: { living Room: { items: ['tv' ,'sofa'] }, bedroom One: { items: ['bed' ,'washing machine'], windows: 3 }, bedroom Two:{ items: ['bed' ,'bed' ,'desk'], windows: 4 }, kitchen:{ items: ['fridge' ,'broken chair' ,'microwave'] } } }; // 添加元素到living Room的items数组末尾 house.areas['living Room'].items.push('dining table'); console.log(house.areas['living Room'].items); // 输出: ['tv', 'sofa', 'dining table']
方法二:用unshift()在数组开头添加
如果你想把元素放到数组最前面,可以用unshift():
house.areas['living Room'].items.unshift('dining table'); console.log(house.areas['living Room'].items); // 输出: ['dining table', 'tv', 'sofa']
方法三:用splice()在指定位置添加
如果要在数组的某个特定索引位置插入元素,比如在索引1的位置(也就是'tv'和'sofa'之间)添加,可以用splice():
// splice(插入位置, 要删除的元素数量, 要添加的元素) house.areas['living Room'].items.splice(1, 0, 'dining table'); console.log(house.areas['living Room'].items); // 输出: ['tv', 'dining table', 'sofa']
内容的提问来源于stack exchange,提问作者Hamsa
相关产品推荐
相关产品推荐

