[英]How to use forEach when there is no array [JavaScript]
I would like to use forEach
in JavaScript.我想在 JavaScript 中使用
forEach
。
sentence.forEach(function(value) {--------
When sentence
is an array, forEach works properly.当
sentence
是一个数组时, forEach 可以正常工作。
{
"sentence": [
{
"word": [
{
"content": "tell"
},
{
"content": "me"
}
]
},
{
"word": [
{
"content": "do"
},
{
"content": "you"
},
{
"content": "want"
}
]
}
]
}
However, when sentence
has only one value and is not an array, forEach doesn't work and it makes error message like this.但是,当
sentence
只有一个值并且不是数组时,forEach 不起作用,它会发出这样的错误消息。 Uncaught TypeError: sentence.forEach is not a function
{
"sentence": {
"word": {
"content": "hello"
}
}
}
I get json object from external API, so I don't know whether sentence
has only one value or many values.我从外部 API 得到 json object,所以我不知道
sentence
是只有一个值还是多个值。 How can I solve this problem?我怎么解决这个问题? Could you give me any information or advice?
你能给我任何信息或建议吗?
Make sure you always have an array, and convert it to an array if it isn't.确保您始终拥有一个数组,如果没有,则将其转换为数组。 You could do something like the following:
您可以执行以下操作:
const sentenceArray = Array.isArray(sentence) ? sentence : [sentence];
Then use sentenceArray instead like so:然后像这样使用 sentenceArray :
sentenceArray.forEach(...
You could convert the data to an array with Array#concat
if it is no array or keep the array.如果它不是数组或保留数组,您可以使用
Array#concat
将数据转换为数组。
[].concat(data).forEach(callback);
For using this approach, you could wrap it in a function getArray
.要使用这种方法,您可以将其包装在 function
getArray
中。
const getArray = value => [].concat(value), callback = ({ word }) => getArray(word).forEach(({ content }) => console.log(content)), a = { sentence: [{ word: [{ content: "tell" }, { content: "me" }] }, { word: [{ content: "do" }, { content: "you" }, { content: "want" }] }] }, b = { sentence: { word: { content: "hello" } } }; getArray(a.sentence).forEach(callback); getArray(b.sentence).forEach(callback);
Split your code conditionally有条件地拆分代码
if(Array.isArray(sentence)
{
//your foreach
}
else
{
//pick relevant properties from sentence object
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.