无法将plain数组转换为jquery数组

时间:2014-07-03 14:47:45

标签: javascript jquery arrays

加载时我必须禁用NEXT按钮,但为此我必须将我的普通数组转换为jquery数组。

http://jsfiddle.net/2hBUq/1/

我试过但它在控制台中显示出一些奇怪的价值。所以请帮我解决这个问题

HTML

<div id="wholeRecipeIds">
    [3618, 5143, 5144, 5146, 9728, 16497, 4002, 4852, 2864, 32661]
</div>
 <input id="next" width="100px" type="button"  value="Next">

jquery的

var nextRowIndex = '32661'; 
var wholeRecipes=$("#wholeRecipeIds").html();
var recipArray = jQuery.makeArray(wholeRecipes); 
var lastRecipeId =  recipArray[recipArray.length-1];

console.log("New array recips:"+recipArray);   
console.log("size of array recipe:"+recipArray.length);   
console.log("lastRecipeId in array :"+lastRecipeId);  
if(nextRowIndex==lastRecipeId){
   $("#next").attr('disabled','disabled');
}

输出:(#34输出错误;数组配方大小&lastRecipeId变量)

New array recips:
    [3618, 5143, 5144, 5146, 9728, 16497, 4002, 4852, 2864, 32661]
 (index):28
size of array recipe:1 
lastRecipeId in array :
    [3618, 5143, 5144, 5146, 9728, 16497, 4002, 4852, 2864, 32661]

为什么这个奇怪的输出。

3 个答案:

答案 0 :(得分:1)

jQuery.makeArray()将类似数组的对象转换为数组

使用JSON.parse()字符串转换为数组。

尝试:

var recipArray = JSON.parse(wholeRecipes); 

而不是

var recipArray = jQuery.makeArray(wholeRecipes); 

DEMO

答案 1 :(得分:1)

你不是从数组开始的;你是从一个字符串开始的。 <div>的内容只读为一个简单的字符串。如果您希望将其解释为数组,可以将其提供给JSON解析器:

    var wholeRecipes = JSON.parse($("#wholeRecipeIds").html());

实际上没有必要这样做:

    var recipArray = jQuery.makeArray(wholeRecipes); 

一旦解析了元素的原始内容,就会有一个JavaScript数组。实际上没有“jQuery数组”这样的东西,而且那不是那个API的用途。

答案 2 :(得分:0)

makeArray 将类似数组的对象转换为真正的JavaScript数组。

    var nextRowIndex = '32661'
        wholeRecipes=$("#wholeRecipeIds").html(),
        recipArray = $.parseJSON(wholeRecipes), 
        lastRecipeId = recipArray[recipArray.length-1];

    console.log("New array recips:"+recipArray);   
    console.log("size of array recipe:"+recipArray.length);   
    console.log("lastRecipeId in array :"+lastRecipeId);  
    if(nextRowIndex==lastRecipeId){
       $("#next").attr('disabled','disabled');
   }