简体   繁体   English

在javascript foreach中使用数组

[英]use array in javascript foreach

I have the following (simplified) php function which calculates a total value for me. 我有以下(简化)的php函数,它为我计算总价值。 it basically fetch an array of items from the wordpress database and checks the type of each item and then compare its value to a specific given value and sums all the comparisons up. 它基本上是从wordpress数据库中获取一个项目数组,并检查每个项目的类型,然后将其值与特定的给定值进行比较,并将所有比较结果求和。

        function total(){ 
        $value1 = 10; // compare value for type 1 items
        $value1 = 20; // type 2 items
        $value1 = 30; // type 3 items
        $total = 0; // reset total variable

global $wpdb;
        $items = $wpdb->get_results("SELECT `item_type` as type, `item_value` as value FROM `table`"); // get all the items from database

        foreach ($items as $item) {

    // check which item type
        switch ($item->type) { 
          case 1:
         $total = $total + min($value1, $item->value);
            break;
          case 2:
          $total = $total + min($value2, $item->value);
            break;
          case 3:
         $total = $total + min($value3, $item->value);
            break;
        }}

        return $total;
        }

Now i want to remake the same function in javascript so i can use it in a form for calculations. 现在,我想在javascript中重新制作相同的函数,以便以某种形式使用它进行计算。 This is what i got so far; 这就是我到目前为止所得到的。

<SCRIPT type="text/javascript">
 function calculate_total (){
    var items = <?php echo json_encode($items); ?>;
    var value1 = document.form.range1Input.value;
    var value2 = document.form.range2Input.value;
    var value3 = document.form.range3Input.value;

  for each (var item in items){
     switch (**(refer to item type in array)**) { 
          case 1:
         total = total + min(value1, **(refer to item value in array)**);
            break;
          case 2:
          total = total + min(value2, **(refer to item value in array)**);
            break;
          case 3:
         total = total + min(value3, **(refer to item value in array)**);
            break;
        }}

 document.form.total.value = total;
}
</script>

How can i refer to the values in the items array? 如何引用items数组中的值? I hope somebody can give me some advice on this one. 我希望有人能给我一些建议。

Also i saw that echo json_encode($items) formats the array as {"type":"3","value":"1.00"},{"type":"1","value":"20.50"} etc etc, I was wondering if this is a usable format for javascript because when i try total = items[1]; 我也看到echo json_encode($items)将数组格式化为{"type":"3","value":"1.00"},{"type":"1","value":"20.50"}等等等,我想知道这是否是JavaScript的可用格式,因为当我尝试total = items[1]; I see [Object Object] in the form. 我在表格中看到[Object Object]

$items = $pdb->get_results() is btw formatted as Array ( [0] => stdClass Object ( [type] => 1 [value] => 35.00 ) [1] => stdClass Object ( [type] => 3 [value] => 1.00 ) $items = $pdb->get_results()被格式化为Array ( [0] => stdClass Object ( [type] => 1 [value] => 35.00 ) [1] => stdClass Object ( [type] => 3 [value] => 1.00 )

You should probably read up on your JavaScript syntax, but there are four ways to loop over an array: 您可能应该阅读JavaScript语法,但是有四种方法可以遍历数组:

TL;DR: if you're doing things that mutate state, I recommend Array#forEach , if not, recommend Array#map . TL; DR:如果您正在做会改变状态的事情,我建议您使用Array#forEach ,否则,建议使用Array#map

var myArray = [1,2,3,4,5,6];
var len = myArray.length;

1) for loop 1)for循环

for (var i=0; i<len; i++) {
  doSomethingTo(myArray[i]);
}

2) while loop 2)while循环

var i = 0; 
while (i<len) {
  doSomethingTo(myArray[i]);
  i++;
}

3) forEach 3)每次

myArray.forEach(function (element) {
  doSomethingTo(element);
});

4) map 4)地图

var newArray = myArray.map(function (element) {
  doSomethingTo(element);
});

Of these four, ONLY map has a return. 在这四个图中,只有map才有回报。 It will run the function you give it on each of the elements of the array, and return an array of those all together. 它将在数组的每个元素上运行您赋予它的函数,并一起返回所有这些元素的数组。 the while loop is the fastest, but you should avoid doing things imperatively like that if you can. while循环是最快的,但是如果可以的话,您应该避免强制执行这样的操作。

Like you speculated, your first item can be referred to as items[0] , second as items[1] , and so on. 就像您推测的那样,您的第一个项目可以称为items[0] ,第二个项目可以称为items[1] ,依此类推。

So, in your switch statement / within your for loop where item refers to the current index (0, 1, 2, etc), you can say items[item] to refer to the item you're currently looking at in your loop: first it will be equal to items[0] , then items[1] , and so on. 因此,在您的for循环中的switch语句中/其中item引用当前索引(0、1、2等),您可以说items[item]引用您当前在循环中查看的项目:首先它将等于items[0] ,然后等于items[1] ,依此类推。

So, switch (items[item].type) { should be what you need. 因此, switch (items[item].type) {应该是您所需要的。


(A quick JS recap: arrays and objects are different things in JS, look up the differences if you're not sure. When referencing them, you can use myArray[0] to get things from an array, and you can use myObject['myKey'] or myObject.myKey to get things from an object. In your case, items is an array , and each of its elements is an object . You can therefore do items[0]['type'] or items[0].type to access the type of your first item). (快速的JS概述:JS中的数组和对象是不同的东西,如果不确定,请查找差异。引用它们时,可以使用myArray[0]从数组中获取内容,也可以使用myObject['myKey']myObject.myKey来从对象中获取内容。在您的情况下, items是一个数组 ,其每个元素都是一个对象,因此可以执行items[0]['type']items[0].type访问您的第一项的类型)。


The reason items[1] just showed [Object object] when you tried it is because browsers aren't great at displaying objects on screen – the object is there, and JS can see it, it's just that most objects are printed as [Object object] . 尝试使用items[1]只显示[Object object]的原因是因为浏览器不太擅长在屏幕上显示对象-该对象在那里,而JS可以看到它,只是大多数对象都被打印为[Object object] You'd be better off displaying JSON.stringify(items[1]) to see a JSON representation of the object as a string. 您最好显示JSON.stringify(items[1])以将对象的JSON表示形式显示为字符串。 Better yet, try console.log(items) or console.log(items[1]) to see the entire object in your browser's console (you can search for how to bring up your browser console, it's different for each browser/OS, but it's brilliant for debugging). 更妙的是,尝试使用console.log(items)console.log(items[1])在浏览器控制台中查看整个对象(您可以搜索如何打开浏览器控制台,每个浏览器/ OS都不一样,但非常适合调试)。

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

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