【问题标题】:How to add the numeric values of properties of a nested array?如何添加嵌套数组属性的数值?
【发布时间】:2014-11-20 20:44:11
【问题描述】:

我试图弄清楚如何创建一个函数来添加用户选择的元素的值,并能够通过提示和 console.log 显示结果。另外,我想知道是否有一种方法可以做到这一点,我不需要指定选择的元素,以便函数在代码中找到选择了哪些元素并执行添加功能。因为很明显,如果选项列表更长,我不想为每个可能的选择组合创建一个新函数。附带说明一下,我想同样的问题也适用于 if 语句,switch 语句是解决该实例中“DRY”代码需求的最有效方法吗?

我的 javascript 代码:请假设用户只选择嵌套数组的第一个元素。此外,“一”这个词值 8 美元。

var selection = new Array (3);
selection[0] = new Array ('$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8');
selection[1] = new Array ('phone1', 'phone2', 'phone3');
selection[2] = new Array ('one', 'two', 'three');


function pickPhone () {
    var yourPhone = prompt("pick phone: phone1: $1, phone2: $2, phone3: $3");

        if (yourPhone == selection[1][0]) {
        console.log(selection[1][0] + " will cost: " + selection[0][0]);
        alert(selection[1][0] + " will cost: " + selection[0][0]);
            pickTerm ();
        } if (yourPhone == "phone2") {
            alert(selection[1][1] + " will cost: " + selection[0][1]);
        } if (yourPhone == "phone3") {
            alert(selection[1][2] + " will cost: " + selection[0][2]);
        }

}


function pickTerm () {
    var yourTerm = prompt("pick term: one, two or three?");

        if (yourTerm == selection[2][0]) {
            alert("Your total so far is: ??");
        }
}

pickPhone ();

非常感谢任何帮助,谢谢。

【问题讨论】:

  • 你最好使用类似的对象:var data = {costs:[1,2,3], phones:[1,2,3], other:[1,2,3]}

标签: javascript arrays function variables operators


【解决方案1】:

保留数组的解决方案

http://jsfiddle.net/OxyDesign/o10ezyun/

JS

var selection = new Array(3);
selection[0] = new Array(1,2,3,4,5,6,7,8);
selection[1] = new Array('phone1', 'phone2', 'phone3');
selection[2] = new Array('one', 'two', 'three');

var firstValue;

function pickPhone() {
    var yourPhone = prompt("pick phone: phone1: $1, phone2: $2, phone3: $3"),
        index = selection[1].indexOf(yourPhone);

    if(!~index){
        pickPhone();
    }else{
        firstValue = selection[0][index];
        alert(selection[1][index] + " will cost: $" + firstValue);
        pickTerm();    
    }
}


function pickTerm() {
    var yourTerm = prompt("pick term: one, two or three?"),
        index = selection[2].indexOf(yourTerm),
        finalValue = '$'+(firstValue+selection[0][index]);

    if(!~index){
        pickTerm();
    }else{
        alert("Your total so far is: "+finalValue);
    }
}

pickPhone();

【讨论】:

  • 这看起来很有希望,我将对此进行调查,并会尽快回复您。谢谢。
  • 是的,我真的不能理解这一点,我想我应该提到我是一个初学者。非常感谢您的帮助!
【解决方案2】:

我不确定您实际解决的是什么问题。 这些清单有多长(电话、费用等)? 为这些项目设置了什么类型的映射?

现在我建议合并对象中的相应值,如下所示:

// item -> cost
var phones = [
        {title: 'phone1', cost: '$1'},
        {title: 'phone2', cost: '$2'},
        {title: 'phone3', cost: '$3'}
    ],

    terms = [
        {title: 'one', cost: '$8'},
        {title: 'two', cost: '$2'},
        {title: 'three', cost: '$3'}
    ],

    phonesListWithCosts = (function(list) {
        return list.reduce(function(memo, item) {
            return memo + item.title + ': ' + item.cost;
        }, '');
    }(phones)),

    termsList = (function(list) {
        return list.reduce(function(memo, item) {
            return memo + ', ' + item.title;
        }, '');
    }(terms)),

    findBy = function(array, property, value) {
        return array.filter(function(item) {
            return item[property] === value;
        })[0];
    },

    getItem = function(list, promptMessage) {
        var selectedItemTitle = prompt(promptMessage);

        return findBy(list, 'title', selectedItemTitle);
    },

    getItemCost = function(item) {
        return parseInt(item.cost.replace(/\D/g, ''), 10);
    },

    pickPhone = function() {
        var selectedPhone = getItem(phones, 'pick phone: ' + phonesListWithCosts),
            firstPhone = phones[0],
            message;

        if (selectedPhone) {
            message = [selectedPhone.title, 'will cost:', selectedPhone.cost].join(' ');

            console.log(message);
            alert(message);

            if (selectedPhone === firstPhone) {
                pickTerm(getItemCost(selectedPhone));
            }
        }
    },

    pickTerm = function(accumCost) {
        var selectedTerm = getItem(terms, 'pick term: ' + termsList),
            totalCost,
            message;

        if (selectedTerm) {
            totalCost = accumCost + getItemCost(selectedTerm);
            message = 'Your total so far is: $' + totalCost;

            alert(message);
        }
    };

pickPhone();

jsbin demo.

【讨论】:

  • 我不能使用开关或对象来做到这一点。
  • 为什么?你能提供更多细节吗?
  • 这是一个学校作业。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 2023-03-05
  • 1970-01-01
  • 2013-10-11
相关资源
最近更新 更多