繁体   English   中英

Object.keys,切片和拼接

[英]Object.keys, slice and splice

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

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怎么来切片工作和拼接不?

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) 

暂无
暂无

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

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