循环通过2d数组的JavaScript

时间:2012-02-02 00:25:16

标签: javascript arrays sorting

我正在尝试解决如何在首先搜索单独的数组元素时从多个数组发布项目,然后仅返回符合特定条件的项目。以下代码尚未执行此操作。

enter code here<div id="myDiv">
<script type="text/javascript">


var $ = function(id) {
    return document.getElementBuId(id);

}
var title = new Array("Barbecuing in the Rain","Picnicing in the Arctic",
        "How to Saute on a Radiator", "A Real Grasshopper: Bartending with Insects",
        "Food with a Bullet:  Cooking in Camden", "Mirepoix for Dummies");
var price = new Array(18.50, 23.95, 41.95, 5.95, 13.00, 99.00);
var binding = new Array("Hardcover", "Paperback", "Hardcover", "Paperback", "Paperback", "Hardcover");
var pubYear = new Array(2002, 1975, 2004, 2006, 2001, 1997);
var NYTBestSeller = new Array(true, true, false, false, true, true)
    var seriesTitle = new Array("Food Network", "The Food Network", 
            "Culinary Shortcuts", "Sunset Libations", 
            "Food Network", "The Food Network");
var bargainBooks = ("Food Network Hot Selling Bargain Book");

for (i in title) {
    if (((price[i] <= 25 && binding[i] == "Hardcover") || 
                (price[i] <= 15 && binding[i] == "Softcover")) && (pubYear[i] >= 2000) && 
            (NYTBestSeller[i] == true) && (seriesTitle[i] == "Food Network") || (seriesTitle[i] == "The Food Network"))


        //document.write("<span color='red'>This line is red</span>");



        document.write(title[i] + "<br />");
    document.write(price[i] + "<br />");
    document.write(binding[i] + "<br />");
    document.write(pubYear[i] + "<br />");
    document.write(NYTBestSeller[i] + "<br />");
    document.write(seriesTitle[i] + "<br />" + "<hr/>");

}
</script>

我正在搜索符合某个标准的图书,然后尝试输出该图书页面上的绿色热销书的消息。但我无法弄清楚如何使document.write工作。 document.write()。style.color =“green”不起作用。

1 个答案:

答案 0 :(得分:3)

document.write只输出文本,你必须在那里写自己的标签(例如div设为绿色)。

但是我建议你采用不同的方法,如果是带有id的空div,请执行以下操作:

document.getElementById('your-div-id').innerHTML = 'text <br /> <span style="color: green;">other text</span> and so on';

还会以更好的方式重新组织代码。

Document.write只会将代码附加到输出流的末尾(本例中为文档),因此您无法指定输出的显示位置。

编辑1: 另外,在这种情况下使用对象呢?据我所知,您使用数组来模拟他们的行为:

var myObjArray = [
    {
        title: 'mytitle1',
        price: '10$',
        binding: 'dunno',
        pubYear: 'dunno-again',
        NYTBestSeller: true,
        seriesTitle: 'Something'
    },
    {
        ...other object data...
    }
]

document.getElementById('your-div-id').innerHTML += myObjArray[0].title + '<br />' + myObjArray[0].price;

希望你能发现它很有趣