为什么会有“未定义"的字样?我的字符串开头的文字? [英] Why is there "undefined" text in the beginning of my string?
问题描述
我有一个将AJAX请求的结果连接在一起的函数.
I have a function that concatenates together the results from an AJAX request.
由于某种原因,我的最终字符串以"undefined"开头.
For some reason, my final string starts with "undefined".
这是一个重现该问题的简化示例:
Here is a simplified example that reproduces the problem:
// In practice, fetched via AJAX from a server
var vendors = [{ id_vendor: 'V0001' }, { id_vendor: 'V0002' }];
var row_vendor;
vendors.forEach(function (value) {
row_vendor += value.id_vendor;
});
alert(row_vendor); // undefinedV0001V0002
为什么警报值显示前导的未定义"?
Why does the value alerted display a leading "undefined"?
推荐答案
您没有初始化变量,因此其值为undefined
.串联字符串后,将其强制为串联之前的字符串"undefined"
.
You're not initializing your variable, so its value is undefined
. Concatenating a string coerces it to the string "undefined"
before the concatenation.
考虑:
var x
alert(x + "test") // undefinedtest
相反,在执行串联之前,请将变量初始化为空字符串:
Instead, initialize your variable to an empty string before performing concatenation:
var x = ""
alert(x + "test") // test
请注意,从功能上讲,首先提取您感兴趣的属性,然后将它们一起join
,这样会更清洁:
Note that functionally it is much cleaner to first extract the property you're interested in and then simply join
them together:
$.map(vendor, function (v) { return v.vendor_id }).join('')
这篇关于为什么会有“未定义"的字样?我的字符串开头的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!