为什么forEach返回undefined但会登录到控制台

时间:2017-10-02 01:58:42

标签: javascript arrays foreach

我正在尝试迭代数组并添加一些HTML标记。我尝试了.map,但由于它返回另一个数组,我可以看到HTML中的逗号。我尝试了.forEach,它在我将其登录到控制台时起作用,但我在HTML中未定义。我搜索了一个答案,发现一些答案指向没有返回调用函数。有些人有回调并且从回叫中返回但不回到调用函数。我找不到我不回来的地方。

我知道wrapTag正在返回,因为我可以将其记录到控制台,但它似乎没有传递给wrappedItems

我是否遗漏了一个回复,或者.forEach是否存在我未正确实施的回复?

$(document).ready(function(){
let objR = {
    key1:"5",
    key2:"8",
    key3:"6",
    key4:"9",
    key5:
        {subKey1:"1",subKey2:"2",subKey3:"3",subKey4:"4"}
}

let arr = [];
let html = '';

const s = x => document.getElementById(x);
const isObject = val => (typeof val === "object") ? true : false;

const keyValueToArray = (obj) => {
    for(let key in obj) {
        let value = obj[key],
             n = [];

        if(!isObject(value)){
            n.push(key, value);
            arr.push(n);
        }
        else{
            arr.push(key);
            keyValueToArray(value);

        }
    }
    return arr;
}

const typeCheck = (x) => {
    console.log(typeof x);
    return x;
}

const wrapTag = (item, tag, i) => isObject(item) ? '<' + tag + '>' + item[0] + ' : ' + item[1] + '</' + tag  +'>' 
                            :'<' + tag +'>' + item + ':</' + tag +'>';

//const wrappedItems = keyValueToArray(objR).map(x => wrapTag(x, 'li'))

const wrappedItems = keyValueToArray(objR).forEach(function(x, i, z){
    var res = wrapTag(x, 'li');
    console.log(res);
    return res;
})

html = '<ul>';
html +=  wrappedItems;
html += '</ul>';
console.log(`html = ${html}`);


s('cards').innerHTML = html;

});

我通过将forEach包装在匿名函数中并使用let声明res来使obj工作。我必须将wrappedItems传递给 const wrappedItems = (obj) => { let res = ''; keyValueToArray(objR).forEach(function(x, i, z){ res += wrapTag(x, 'li'); console.log(res); }); return res; } html = '<ul>'; html += wrappedItems(objR); html += '</ul>'; 函数,但这与我想要实现的目标并不相同。 这是修改后的功能。

// APP.js 

// Grid cell
const Cell = props => (
  <div>{props.children}</div>
);

Cell.propTypes = {
  area: PropTypes.string.isRequired,
  color: PropTypes.string.isRequired,
};

export default () => (
  <div className={css.container}>
    
    <h2>Grid</h2>
    <Grid

      A={props => <Cell area={props.area}><HeaderLoggedIn /></Cell>}
      B={props => <Cell area={props.area}><EditorButtonBar /></Cell>}
      C={props => <Cell area={props.area}><EditorPreviewBar /></Cell>}
      D={props => <Cell area={props.area}><EditorSidebarLogin /></Cell>} />
      
  </div>
);

1 个答案:

答案 0 :(得分:0)

forEach()没有返回任何内容,因此wrappedItems未定义。 (docs)。您可以尝试使用map()

keyValueToArray(objR).map(function(x, i, z){}

或推送到forEach()

内的新阵列

编辑:

一旦您映射了这些值,就可以使用join()将它们组成一个不带逗号的字符串,如下所示:

html +=  wrappedItems.join(" "); // or whatever you want to join with (maybe "\n")

这应该给你:

<ul><li>key1 : 5</li> <li>key2 : 8</li> ...