javascript - 在数组范围内查找索引

标签 javascript jquery arrays sorting

我有一个数量数组,我想在这个数组中找到一个数字。因此,如果用户输入 16,该函数将在索引 6 和 7 之间返回,因为 16 大于 15 但小于 20。

从更广泛的 Angular 来看,该索引将用于查找所需数量的价格范围。

编辑

HTML 标记

<table cellpadding="0" cellspacing="0" border="0">
    <tbody><tr>
        <th scope="row">Quantity</th>
        <th id="js-QuantityID-0" scope="col">0</th>
        <th id="js-QuantityID-1" scope="col">1</th>
        <th id="js-QuantityID-2" scope="col">2</th>
        <th id="js-QuantityID-3" scope="col">3</th>
        <th id="js-QuantityID-4" scope="col">4</th>
        <th id="js-QuantityID-5" scope="col">5</th>
        <th id="js-QuantityID-6" scope="col">10</th>
        <th id="js-QuantityID-7" scope="col">15</th>
        <th id="js-QuantityID-8" scope="col">20</th>
        <th id="js-QuantityID-9" scope="col">30</th>
        <th id="js-QuantityID-10" scope="col">40</th>
        <th id="js-QuantityID-11" scope="col">50</th>
        <th id="js-QuantityID-12" scope="col">60</th>
    </tr>
    <tr>
        <th scope="row">Price (inc. VAT)</th>
        <td id="js-PriceID-0">0.00</td>
        <td id="js-PriceID-1">45.60</td>
        <td id="js-PriceID-2">38.40</td>
        <td id="js-PriceID-3">32.40</td>
        <td id="js-PriceID-4">34.56</td>
        <td id="js-PriceID-5">30.72</td>
        <td id="js-PriceID-6">26.80</td>
        <td id="js-PriceID-7">21.60</td>
        <td id="js-PriceID-8">20.60</td>
        <td id="js-PriceID-9">17.60</td>
        <td id="js-PriceID-10">16.60</td>
        <td id="js-PriceID-11">15.60</td>
        <td id="js-PriceID-12">14.00</td>
    </tr>
    </tbody>
</table>

工作脚本

function getTableContents() {
    var productArray = [];

    jQuery("th[id^='js-QuantityID-']").each(function () {
        var n = jQuery(this).attr("id").replace('js-QuantityID-', ''); // get the number from the id

        productArray.push({
            qty: parseInt(jQuery(this).text()),
            price: parseFloat(jQuery('#js-PriceID-' + n).text().replace('£',''))
        });
    });

    return productArray = cleanArray(productArray);
}

回答

问题是由于将数量作为字符串获取,在解析为整数时这解决了我的问题@Michael Geary

最佳答案

在您的示例中设置具有匹配元素的并行数组(例如 pricequantity 数组)通常不是一个好主意。这很容易出错,并且很难直观地匹配价格与数量。

相反,您应该使用单个数组,其中每个数组元素都是一个组合了数量级别和价格的对象:

var priceBands = [
    { qty:  1, price: '£45.60' },
    { qty:  2, price: '£38.40' },
    { qty:  3, price: '£32.40' },
    { qty:  4, price: '£32.10' },
    { qty:  5, price: '£34.56' },
    { qty: 10, price: '£30.72' },
    { qty: 15, price: '£26.80' },
    { qty: 20, price: '£21.60' },
    { qty: 30, price: '£21.00' },
    { qty: 40, price: '£21.00' }
];

现在很容易看出哪个价格对应哪个数量,并且两个数组中的元素数量相同是毫无疑问的。

(顺便说一句,我很好奇为什么 5 件商品的价格上涨!)

如果该符号看起来太乏味,您可以轻松地简化它:

var priceBands = makePriceBands([
    ' 1: £45.60',
    ' 2: £38.40',
    ' 3: £32.40',
    ' 4: £32.10',
    ' 5: £34.56',
    '10: £30.72',
    '15: £26.80',
    '20: £21.60',
    '30: £21.00',
    '40: £21.00',
]);

这会生成与前面列出的对象相同的数组,使用此函数转换更简洁的表示法:

function makePriceBands( bandsIn ) {
    var bands = [];
    for( var i = 0;  i < bandsIn.length;  ++i ) {
        var band = bandsIn[i].split(/: */));
        bands.push({ qty: +band[0], price: band[1] });
    }
    return bands;
}

对于现代浏览器,你可以写得更简单一点:

function makePriceBands( bands ) {
    return bands.map( function( b ) {
        var band = b.split(/: */));
        return { qty: +band[0], price: band[1] };
    });
}

但第一个版本可以在任何旧浏览器上运行。

无论哪种方式,找到合适价格的代码都很简单。向后遍历数组,直到到达输入数量大于或等于数组元素中数量的元素。

我们将使它成为一个需要 prices 数组作为参数的函数,因此您可以通过传入不同的数组来将它用于不同的产品。

此外,您没有在问题中指定当输入数量等于其中一个价格水平数量时要做什么,所以我假设,例如,如果您有10 个或更多,您获得数量 10 的价格水平。(换句话说,您不必购买 11 个以获得数量 10 的价格。)

function priceForQuantity( prices, n ) {
    for( var i = prices.length - 1;  i >= 0;  --i ) {
        if( n >= prices[i].qty ) {
            return prices[i].price;
        }
    }
    return '£0.00';
}

或者您可以向前走遍数组,但我发现向后走更容易思考这个特定问题。

您可以使用一些示例数量来测试此代码,确保测试比特定数量水平大一和小一的边界条件:

function test( n ) {
    console.log( n, priceForQuantity( priceBands, n ) );
}

test( 0 );
test( 1 );
test( 3 );
test( 5 );
test( 6 );
test( 9 );
test( 10 );
test( 39 );
test( 40 );
test( 41 );

这将记录:

0 "£0.00"
1 "£45.60"
3 "£32.40"
5 "£34.56"
6 "£34.56"
9 "£34.56"
10 "£30.72"
39 "£21.00"
40 "£21.00"
41 "£21.00"

关于javascript - 在数组范围内查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119416/

相关文章:

javascript - 使用函数将值传递到 jQuery UI 对话框

jquery - 日期选择器选定的值始终出现在第一个文本框中

c++ - 如何从函数返回动态分配的指针数组?

javascript - 如何将两个数组组合成一个具有键值对的对象?

javascript - JQuery onClick 只工作一次

javascript - 如何通过 GmailApp 检索已发送电子邮件的 ID?

javascript - JQuery 在 2 个函数中将参数作为变量传递返回未定义

javascript - HTML5 Canvas - 如何在 Canvas 中的图像上绘制矩形

javascript - jQuery - 调整浏览器窗口大小后自动更改值

c - 在元素上拆分 C 数组