简体   繁体   English

如何正确检查索引是否存在,然后使用index获取值,然后从数组javascript / jquery中删除索引和值

[英]How to properly check if index exists, then use index to get value, then delete index & value from array javascript/jquery

I know the title was a mouthful, but describes what I need to do here. 我知道标题是满口的,但描述了我在这里需要做的事情。 I will admit I'm having a lot of trouble figuring this out! 我会承认我在解决这个问题上遇到了很多麻烦!

I'm trying to create a discount calculator and this is my first time using arrays. 我正在尝试创建折扣计算器,这是我第一次使用数组。

Here's the code I have so far... 这是我到目前为止的代码......

    dTrackerArray = [];
    //Create Array

    dTrackerArray.push( [var1, var2] );
    //Add Variables to Array

    var check = $.inArray(var1, dTrackerArray);
    // Checking to see if variable exists, keeps returning -1!!!

    alert(JSON.stringify(dTrackerArray));
    // Even though I have this right under it which alerts the array clearly showing var 1 and var 2 exist!

Once I've figured out how to properly check the array, I'd like to retain the value of the pair (in a variable perhaps), and then remove the pair from the array. 一旦我弄清楚如何正确检查数组,我想保留该对的值(可能在一个变量中),然后从数组中删除该对。

I'm sorry If this was a little hard to read or understand! 对不起如果这有点难以阅读或理解!

You're creating a multidimensional array ( [var1, var2] becomes an object within the dTrackerArray array.) 您正在创建一个多维数组( [var1, var2]成为dTrackerArray数组中的一个对象。)

Try pushing var1 and var2 separately. 尝试分别推送var1var2

 dTrackerArray.push(var1);
 dTrackerArray.push(var2);

You are adding an array that contains var1 and var2 to the dTrackerArray array. 您正在向dTrackerArray数组添加包含var1var2的数组。

Use this syntax instead: 请改用此语法:

dTrackerArray.push(var1);
dTrackerArray.push(var2);

// Or this syntax
dTrackerArray.push(var1, var2);

// Or this syntax
dTrackerArray = [ var1, var2 ];

Here's a working fiddle to demonstrate. 这是一个工作小提琴演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM