gpt4 book ai didi

javascript - 数组转换为字符串

转载 作者:行者123 更新时间:2023-11-30 19:27:21 29 4
gpt4 key购买 nike

我有以下代码,它返回一个数组:

const authorsName = [];
this.props.authors.map((e) => authorsName.push(e.name + ' ' + e.surname));
console.log(authorsName)
// ["Jonh Snow", "Jonh Rain"]

但是当我尝试使用以下代码发送这个数组时:

const s = document.createElement('script');
s.type = 'text/javascript';
s.innerHTML = `window.customConfig.push({
page_type: "article",
article_authors: "${authorsName}"
})`;

authorsName 数组变成下一个字符串:

article_authors: "Jonh Snow,Jonh Rain",

我不明白为什么会这样。拜托,你能告诉我是什么问题吗?提前致谢。

最佳答案

首先,Array.map()的用法这种方式可行,但不太正确。请记住,.map() 返回一个新数组,其中每个元素都以某种方式从原始数组派生而来,并且不会改变原始数组。因此,如果您执行以下操作会更好:

const authorsName = this.props.authors.map(e => e.name + ' ' + e.surname);

另一种选择是使用 Array.forEach() 使代码与您提供的代码更相似。这样:

const authorsName = [];
this.props.authors.forEach(e => authorsName.push(e.name + ' ' + e.surname));

现在,你的下一个代码:

s.innerHTML = `window.customConfig.push({
page_type: "article",
article_authors: "${authorsName}"
})`;

使用 Array.toString()authorsName 数组强制转换为字符串方法和 MDN 接下来是这样说的:

For Array objects, the toString method joins the array and returns one string containing each array element separated by commas. JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

因此,您需要使用 JSON.stringify()将数组转换为它的 JSON 表示形式。

s.innerHTML = `window.customConfig.push({
page_type: "article",
article_authors: "${JSON.stringify(authorsName)}"
})`;

您可以在下一个示例中检查使用 toString()JSON.stringify() 之间的区别:

let arr = [1,2,3];

console.log("With toString() =>", arr.toString());
console.log("With JSON.stringify() =>", JSON.stringify(arr));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

关于javascript - 数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56764231/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com