简体   繁体   English

有没有办法对 Javascript 中的数组中的每个奇数和偶数 object 进行排序?

[英]Is there a way to sort each odd and even object in an array in Javascript?

I need to be able to append every even object on the left side of a vertical line, and every odd object on the right side.我需要能够在垂直线的左侧每偶数 object 和右侧的每奇数 object 上 append。 I am not sure how I can achieve this.我不确定如何实现这一目标。 Sample of the JSON, (This is just dummy data for now) (url) JSON 的样本,(目前这只是虚拟数据)(网址)

[{
        "Year": 2010,
        "Title": "Cadillac",
        "Description": "Escalade ESV"
    },
    {
        "Year": 1998,
        "Title": "Volvo",
        "Description": "V70"
    },
    {
        "Year": 1992,
        "Title": "Toyota",
        "Description": "Camry"
    },
    {
        "Year": 2012,
        "Title": "Ford",
        "Description": "Explorer"
    }]

Heres my code:这是我的代码:

fetch(url)
.then(result => {
  return result.json();
})
.then (data =>{
  console.log(data);
  data.forEach( (point) => {
      const appendToHtml =  `
      <div class="container left">
            <div class="content">
                <h2>${point.Title}</h2>
                <p>${point.Description}</p>
                <p>${point.Year}</p>
            </div>
        </div>
        <div class="container right">
            <div class="content">
                <h2>${point.Title}</h2>
                <p>${point.Description}</p>
                <p>${point.Year}</p>
            </div>
        </div>
            `;
      $(".timeline").append(appendToHtml);
    });
  })

The issue is it append on the left AND the right.问题是左侧和右侧的 append。 Click here for an image of the issue.单击此处查看问题的图像。 I need to alternate for example Cadillac on the left, Volva on the right etc... I cant seem to figure out what to do..我需要交替,例如左边的凯迪拉克,右边的 Volva 等等......我似乎不知道该怎么做......

Thanks in advance!提前致谢!

You can calculate the odd or even of car index and based on that apply class left and right .您可以计算汽车指数的奇数或偶数,并在此基础上应用 class leftright

data.forEach( (point, index) => {
  const isOdd = index % 2;
  const appendToHtml =  `
  <div class="container ${isOdd ? 'right' : 'left' }">
        <div class="content">
            <h2>${point.Title}</h2>
            <p>${point.Description}</p>
            <p>${point.Year}</p>
        </div>
    </div>`;
  $(".timeline").append(appendToHtml);
});

Here you go with a solution给你go一个解决办法

 fetch(url).then(result => { return result.json(); }).then (data =>{ console.log(data); data.forEach( (point, i) => { const appendToHtml = ` <div class=`container ${i%2 === 0? "right": "left" }`> <div class="content"> <h2>${point.Title}</h2> <p>${point.Description}</p> <p>${point.Year}</p> </div> </div> `; $(".timeline").append(appendToHtml); }); })

Use template literal for finding odd even using mod function使用模板文字查找奇偶使用 mod function

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

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