繁体   English   中英

遍历 object 中的数组并推送到 Javascript 中的新数组

[英]Loop through array within an object and push to a new array in Javascript

我正在尝试遍历作为数组的对象的值,并打印出具有匹配 dollParts1 或 dollParts2 的完整集合的玩偶名称。

例如,如果 dollParts1 在参数中,["Betty", "Alice"] 应该打印出来,因为这些是唯一具有所有特定部分(眼睛、鼻子、嘴巴、耳朵)的娃娃。

但我的解决方案是打印出所有娃娃的名字,我不知道为什么。 我觉得我没有正确使用休息。 我也尝试了“return false”而不是break,但它完全退出了for循环,这也是我不想要的。

let dollObject = {
  Betty: [ 'feet', 'eyes', 'nose', 'ears', 'mouth' ],
  Carol: [ 'nose', 'nose', 'arms', 'nose', 'mouth' ],
  Lisa: [ 'eyes', 'nose', 'feet', 'hands' ],
  Alice: [ 'eyes', 'mouth', 'nose', 'ears', 'eyes' ]
}

let dollType1 = "eyes,nose,mouth,ears"
let dollType2 = "eyes,nose,mouth,ears,feet"

let result = []
let dollParts1 = dollType1.split(",")
let dollParts2 = dollType2.split(",")

function createDoll(whichPart) {
    for (doll in dollObject) {
      for (let i = 0; i < whichPart.length; i++) {
        if (!dollObject[doll].includes(whichPart[i])) {
          break;
        } 
      }
      result.push(doll)
    }
    console.log(result)
}

createDoll(dollParts1)

内循环什么都不做。 本节

for (let i = 0; i < whichPart.length; i++) {
  if (!dollObject[doll].includes(whichPart[i])) {
    break;
  } 
}

也可能根本不存在,因为那里的所有行实际上都没有任何事情——无论你是否提前退出内部循环都没有区别,因为在内部循环完成后,无论如何你都会推送该值。

检查给定娃娃名称的每个部分是否包含在娃娃类型.every之一中。

 const dollObject = { Betty: [ 'feet', 'eyes', 'nose', 'ears', 'mouth' ], Carol: [ 'nose', 'nose', 'arms', 'nose', 'mouth' ], Lisa: [ 'eyes', 'nose', 'feet', 'hands' ], Alice: [ 'eyes', 'mouth', 'nose', 'ears', 'eyes' ] } let dollType1 = "eyes,nose,mouth,ears" let dollType2 = "eyes,nose,mouth,ears,feet" let result = [] let dollParts1 = dollType1.split(",") let dollParts2 = dollType2.split(",") function createDoll(whichPart) { return Object.keys(dollObject).filter(name => whichPart.every( part => dollObject[name].includes(part) )); } console.log(createDoll(dollParts1));

在这个问题中,您可以使用every ,它会检查每个部分是否都包含在娃娃中

 let dollObject = { Betty: ["feet", "eyes", "nose", "ears", "mouth"], Carol: ["nose", "nose", "arms", "nose", "mouth"], Lisa: ["eyes", "nose", "feet", "hands"], Alice: ["eyes", "mouth", "nose", "ears", "eyes"], } let dollType1 = "eyes,nose,mouth,ears" let dollType2 = "eyes,nose,mouth,ears,feet" let dollParts1 = dollType1.split(",") let dollParts2 = dollType2.split(",") function createDoll(whichPart) { let result = [] for (doll in dollObject) { if (whichPart.every(part => dollObject[doll].includes(part))) { result.push(doll) } } console.log(result) } createDoll(dollParts1)

暂无
暂无

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

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