.length 是对 JavaScript 数组的适当调用吗?
2016-09-14
72
出于某种原因,我无法获取数组的长度(如果数组中没有元素,则表示数组长度未定义,对吗?)。
define(function() {
'use strict';
var self = {},
events = {};
self.publish = function publish(eventName, data) {
var subscribers, x, length;
if (events[eventName]) {
return false;
}
subscribers = events[eventName];
for (x = 0, length = subscribers.length || 0; x < length; x += 1) {
subscribers[x](data);
}
return true;
};
self.subscribe = function subscribe(eventName, func) {
if (!events[eventName]) {
events[eventName] = [];
}
events[eventName].push(func);
};
return self;
});
JSLint 提示:“应为 ';',但实际看到的是 ','。” Jasmine 提示“TypeError:无法读取未定义的属性 'length'”
为什么长度未设置为 0?我误解了这里的语法和操作吗?
3个回答
您在
publish
函数中缺少否定:
self.publish = function publish(eventName, data) {
var subscribers, x, length;
if (events[eventName]) { // <= Here you exit if there are subscribers, and continue if there arent
return false;
}
subscribers = events[eventName]; // So subscribers is guaranteed to be undefined
// can't get length (or any property) of undefined
for (x = 0, length = subscribers.length || 0; x < length; x += 1) {
...
这会导致您的测试失败。这是解决方法:
self.publish = function publish(eventName, data) {
// you can use const and let
// you are storing subscribers in a variable anyway, so why not doing it
// before the check?
const subscribers = events[eventName];
if (!subscribers) {
return false;
}
// you don't need to cache length in a variable, iirc it only improves performance slightly on IE browsers
// neither need you `|| 0`
// there other ways iterating through an array, see for..of and Array.prototype.forEach
for (let x = 0; x < subscribers.length; x++) {
subscribers[x](data);
}
return true;
};
it is undefined if it's unpopulated, right?
不,如果数组为空,则其长度为零。读取对象缺少的属性时会得到未定义的结果,但数组的长度始终是数字。
Tamas Hegedus
2016-09-14
我认为问题出在这行:
for (x = 0, subscribers.length || 0; x < length; x += 1) {
你定义了变量“length”,但从未初始化/分配数据给它。
详细信息:
subscribers.length || 0
这应该做什么?
x < length
x < length or x < subscribers.length?
Don Bhrayan Singh
2016-09-14
事实证明,当我修复了拼写错误后,代码运行良好。
if (events[eventName]) {
应该是
if (!events[eventName]) {
修复后,一切都按预期运行。 我的调试问题总是一些微不足道的小问题
Ken Ingram
2016-09-15