正在javascript中检索keys值

Retrieving the keys value in javascript

本文关键字:keys 检索 javascript 正在      更新时间:2023-09-26

我正在尝试显示api响应中键的值。我的代码看起来像

if(response[0].status == "Success")
            {
                alert('success');
            }
            else
            {
                var texts = "";
                for (reasons in response[0].error_reason) {
                    texts += reasons+";";
            }
                alert(texts);
            }

我在这里的键是"item",它的值是"Choose an valid item"。我想打印警报中的值。BUt当我试图提醒它显示的是键(项)而不是值。如何在此处显示键值。也可以有多个类似键的项目。

正如您所提到的,JavaScript中的foreach循环通过键进行迭代,这意味着代码中的reasons变量将在每次迭代后设置为一个新键。为了访问该值,只需使用reasons变量作为索引,如下所示:

var texts = "";
for (reasons in response[0].error_reason) {
    texts += reasons + " = " + response[0].error_reason[reasons] +";";
}    

然而,您应该小心使用Javascript中的foreach,因为它遍历对象的所有属性,包括对象原型的函数,例如,您最终会将indexOf作为循环中的键。为了避免这种情况,您应该检查值的类型:

var texts = "";
for (reasons in response[0].error_reason) 
    if(typeof(response[0].error_reason[reasons]) !== 'function')
        texts += reasons + " = " + response[0].error_reason[reasons] +";";

这应该按预期工作。