【问题标题】:Object.keys, slice and spliceObject.keys、切片和拼接
【发布时间】:2018-04-24 07:06:40
【问题描述】:

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

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.问题为什么 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));
})

【问题讨论】:

  • something.candy 已经是一个数组。不要在上面使用Object.keys,直接使用过滤器即可:something.candy.filter( function(obj) { obj.name; } )
  • slice 工作,因为有函数 String.prototype.slicesplice 不工作,因为没有函数 String.prototype.splice。因为name 是一个字符串。只有数组有splice
  • 我现在明白了,非常感谢!!!! @ibrahimmahrir

标签: javascript arrays object splice


【解决方案1】:

在学习这一点时,将每个部分分开并查看它会很有帮助。例如你有一个对象:

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) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2016-03-27
    • 2016-07-17
    相关资源
    最近更新 更多