让我们来看看这个问题:
- 给定一个值数组:
values = [3,3.14,4.3,8,9,19,23,24,46,54,87];
.
- 我们希望根据大于 10 的值过滤结果。
- 最后在警报对话框中输出结果(接受一个字符串)。
第一步是进行过滤,然后如何将结果转换为字符串以应用到alert()
函数。
(function() {
var i, len, values, value, results, string_value;
values = [3,3.14,4.3,8,9,19,23,24,46,54,87];
results = []; // Empty array which we will build in order during the filter
for (i = 0, len = values.length; i < len; i++) {
value = values[i]; // Not needed; used for readability
if (value > 10) {
results.push(value); // Add this value to the results array
}
}
// Now that we have a result lets convert that to a string
string_value = results.join(", ");
// And output the result with some string concatenation
alert("Filtered results: [ " + string_value + " ]");
// The use of string_value is optional, you could in-line
// this into the alert line
})();