You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在forEach函数中获取元素属性?为数组元素添加head数据

如何为数组元素添加head属性?

当然可以,但你当前的数组元素是字符串原始值,JavaScript里的原始类型(字符串、数字、布尔等)没法直接添加自定义属性——你试着给字符串加head属性时,JS会临时把它包装成String对象,但这个包装对象用完就销毁了,所以下次访问还是undefined。

解决办法很简单,把数组元素改成对象就行,每个对象里存你需要的字符串内容和head属性:

const foreachfunc = (data = null) => {
    data.forEach((element, index) => {
        console.log('element value = ' + element.value, 'index = ' + index)
        let head = element.head
        console.log(head)
    });
};

// 改成对象数组,每个对象包含value和head属性
const myarray = [
    { value: "test1", head: "自定义head1" },
    { value: "test2", head: "自定义head2" }
]

foreachfunc(myarray)

运行这段代码会输出:

element value = test1 index = 0
自定义head1
element value = test2 index = 1
自定义head2

如果你非要用字符串类型(不推荐),可以手动创建String包装对象,但这种方式实用性很低,因为每次访问都要重新处理,示例如下:

const myarray = [new String("test1"), new String("test2")]
myarray[0].head = "head1"
myarray[1].head = "head2"

foreachfunc(myarray)

不过这种方法没必要,对象数组是更清晰、更常用的方案。

内容的提问来源于stack exchange,提问作者Marco Niebuhr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:01:08