我正在尝试编写一个接受字符串列表或单个字符串的函数.如果它是一个字符串,那么我想将它转换为只有一个项目的数组.然后我可以循环它而不用担心错误.
那么我该如何检查变量是否是一个数组?
我已经完成了下面的各种解决方案,并创建了一个jsperf测试.
我想知道jQuery如何构造其类似数组的对象.我正在尝试解决的关键是它如何设法让控制台将其解释为数组并将其显示为这样.我知道它与长度属性有关,但在玩了一下后我无法弄明白.
我知道这比像对象这样的普通数组没有技术优势,如下例所示.但我认为,当用户进行测试和调试时,这是一个重要的语义元素.
像Object这样的普通数组.
function foo(){
// Array like objects have a length property and it's properties use integer
// based sequential key names, e.g. 0,1,2,3,4,5,6 just like an array.
this.length = 1;
this[0] = 'hello'
}
// Just to make sure add the length property to the prototype to match the Array
// prototype
foo.prototype.length = 0;
// Give the Array like object an Array method to test that it works
foo.prototype.push = Array.prototype.push
// Create an Array like object …Run Code Online (Sandbox Code Playgroud) 所以我有一个简单的Signalr/Knockout项目,它使用映射插件将一个简单的对象(带有更多项的数组的项)绑定到我在JS中定义的viewModel:
var someObjectMapping = {
'MyItemArray': {
create: function (options) {
return new MyItemViewModel(options.data);
}
}
}
var myItemMapping = {
'ItemChildren': {
create: function (options) {
return new ItemChildViewModel(options.data);
}
}
}
var SomeObjectViewModel = function (data) {
ko.mapping.fromJS(data, someObjectMapping, this);
}
var MyItemViewModel = function (data) {
ko.mapping.fromJS(data, myItemMapping, this);
}
var ItemChildViewModel = function (data) {
ko.mapping.fromJS(data, null, this);
}
Run Code Online (Sandbox Code Playgroud)
我使用SignalR的默认设置连接到我的集线器,如下所示:
var myHubProxy = $.connection.myHub;
myHubProxy.client.processSomeObject = function(someObject) {
console.log('SomeObject received');
var viewModel = new SomeObjectViewModel(someObject);
ko.applyBindings(viewModel); …Run Code Online (Sandbox Code Playgroud) 我已将以下方法添加到Array原型中:
Array.prototype.foreach = function(func){
for(var i = 0; i < this.length; i++){
if(!func(this[i]) === false) break; //return false from func in order to break the loop
}
return this;
}
Run Code Online (Sandbox Code Playgroud)
在同一个文件中,在上面的代码之后,我有以下jQuery插件:
jQuery.fn.addClassForEvents = function(){
var that = this;
arguments.foreach(function(event){
that.bind(event[0], function(){
that.addClass(event[0]);
})
.bind(event[1], function(){
that.removeClass(event[0]);
});
});
return this;
}
Run Code Online (Sandbox Code Playgroud)
为了使用这个jQuery插件,我的代码看起来像:
$('div').addClassForEvents(['mouseenter', 'mouseleave']);
Run Code Online (Sandbox Code Playgroud)
但是,浏览器在jQuery插件的"arguments.foreach(...."行中抛出一个错误,简单地说明了
对象#没有方法'foreach'
然而,该foreach方法适用于我的代码的其他地方.为什么在这个jQuery插件中未定义?