gpt4 book ai didi

javascript - Object.keys、切片和拼接

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:09 25 4
gpt4 key购买 nike

所以我还在学习数组和对象,有点卡壳了。 我做了一个对象数组的例子:

var something = {candy:[{name:"snickers", price:2},
{name:"bounty", price:3},
{name:"mars", price:4}]};

Object.keys(something.candy).filter(function(obj){
return console.log(something.candy[obj].name);
})

<强>1。问题 - 为什么我写的时候不起作用。:

var candy1 = Object.keys(something.candy);
candy1.filter(function(obj){
return console.log(obj.name);
});

是不是和上面的代码意思差不多?

2.Question slice为什么起作用而splice不起作用???

Object.keys(something.candy).filter(function(obj){
return console.log(something.candy[obj].name.slice(0,3));
})

Object.keys(something.candy).filter(function(obj){
return a(something.candy[obj].name.splice(1,3));
})

最佳答案

在学习这个的时候,把每一部分都拆开来看一下会很有帮助。例如你有一个对象:

var something = {candy:[{name:"snickers", price:2},
{name:"bounty", price:3},
{name:"mars", price:4}]};

// what is something.candy:

console.log("candy:", something.candy)

// an array -- so what do you get with Object.keys?

var candy1 = Object.keys(something.candy)
console.log("keys:", candy1)

// just the indexes!

// So when you try to filter
candy1.filter(function(obj){
// there is no obj.name becuase each object is just a number
return console.log(obj);
});

我想你只想这样做:

var something = {candy:[{name:"snickers", price:2},
{name:"bounty", price:3},
{name:"mars", price:4}]};

var select = something.candy.filter(obj => {
console.log(obj.name) // look at them all
return obj.name === "mars" // just pick this one
})

console.log("filtered: ", select)

关于javascript - Object.keys、切片和拼接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47233175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com