JS 陣列排序範例
馬老師離開待了約十幾年的教學界,目前在外商科技公司擔任Senior Consultant的工作,原因當然很多,未來有空再慢慢發文章分享,剛好最近有點時間,怕以後忘記,把最近專案中用到的一些程式筆記下來,如果大家有需要,也可以參考使用,這一篇是關於Javascript陣列排序的部分。
通常若有較多的內容需要儲存,變數就沒有陣列來的好用,所以陣列是拿來儲存大量的資料時所使用的,且儲存在裡面的資料,還可以選擇經過排序之後再呈現至畫面上,例如:
var name = ["stanley", "jack", "anita" , "mary"]; name.sort() //依照字母排序 console.log(name); // 輸出 ["anita", "jack", "mary", "stanley"] names.reverse() //反轉陣列內容 console.log(name); //輸出 ["stanley", "mary", "jack", "anita"]
但若我們同時有多個陣列,但希望以其中之一的內容排序時,也可以同步更新到另外一個陣列,該如何處理呢?可以參考以下的方式:
var name = ["stanley", "jack", "anita" , "mary"]; var gender = ["male" , "male" , "female" , "female"]; var score = [30, 10, 40 , 80]; var ID = ["S1" , "S2" , "S3" , "S4"]; console.log("name : " + name + "; score : " + score + "; gender : " + gender + "; ID : " + ID); /* 排序前 name : stanley,jack,anita,mary; score : 30,10,40,80; gender : male,male,female,female; ID : S1,S2,S3,S4; */ var list = []; for (var i = 0; i < name.length; i++){ list.push({ 'name': name[i], 'score': score[i], 'gender': gender[i], 'ID': ID[i] }); } list.sort(function(a, b) { return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1)); }); for (var i = 0; i < list.length; i++) { name[i] = list[i].name; score[i] = list[i].score; gender[i] = list[i].gender; ID[i] = list[i].ID; } console.log("name : " + name + "; score : " + score + "; gender : " + gender + "; ID : " + ID); /* 排序後 name : anita,jack,mary,stanley; score : 40,10,80,30; gender : female,male,female,male; ID : S3,S2,S4,S1; */
若是希望按照分數排序,則可以將sort function 修改為下:
//score 由小到大 list.sort(function(a, b) { return a.score - b.score }); //score 由大到小 list.sort(function(a, b) { return b.score - a.score });
補充:
上述的排序內容均以英文和數字為主,若是遇到中文可使用localeCompare進行,而排序的方式是漢語拼音順序,以下為範例:
var arr = ["二","五","四","一","三"]; //漢語拼音:一[yi], 二[er], 三[san], 四[si], 五[wu] console.log("排序前:" + arr); // 排序前:二,五,四,一,三 arr.sort(function(a,b){ return a.localeCompare(b, 'zh'); //排序後:二,三,四,五,一 }); console.log("排序後:" + arr); var arr = ["中文","英語","法國話", "京片子", "中國"]; //中文[zhong wen], 英語[ying yu], 法國話[fa guo hua], 京片子[jing pian zi], 中國[zhong guo] console.log("排序前:" + arr); //排序前:中文,英語,法國話,京片子,中國 arr.sort(function(a,b){ return a.localeCompare(b, 'zh'); }); console.log("排序後:" + arr); //排序後:法國話,京片子,英語,中國,中文 var arr = ["中文","英语","法国话", "京片子", "中国"]; console.log("排序前:" + arr); //排序前:中文,英语,法国话,京片子,中国 arr.sort(function(a,b){ return a.localeCompare(b, 'zh'); }); console.log("排序後:" + arr); //排序後:法国话,京片子,英语,中国,中文
Сервисный центр предлагает ремонт роботов пылесосов tp-link адреса ремонт роботов пылесосов tp-link рядом
Sea robins are fish with ‘the wings of a bird and multiple legs like a crab’
kra8 cc
Some types of sea robins, a peculiar bottom-dwelling ocean fish, use taste bud-covered legs to sense and dig up prey along the seafloor, according to new research.
Sea robins are so adept at rooting out prey as they walk along the ocean floor on their six leglike appendages that other fish follow them around in the hope of snagging some freshly uncovered prey themselves, said the authors of two new studies published Thursday in the journal Current Biology.
David Kingsley, coauthor of both studies, first came across the fish in the summer of 2016 after giving a seminar at the Marine Biological Laboratory in Woods Hole, Massachusetts. Kingsley is the Rudy J. and Daphne Donohue Munzer Professor in the department of developmental biology at Stanford University’s School of Medicine.
Before leaving to catch a flight, Kingsley stopped at a small public aquarium, where he spied sea robins and their delicate fins, which resemble the feathery wings of a bird, as well as leglike appendages.
“The sea robins on display completely spun my head around because they had the body of a fish, the wings of a bird, and multiple legs like a crab,” Kingsley said in an email.
“I’d never seen a fish that looked like it was made of body parts from many different types of animals.”
Kingsley and his colleagues decided to study sea robins in a lab setting, uncovering a wealth of surprises, including the differences between sea robin species and the genetics responsible for their unusual traits, such as leglike fins that have evolved so that they largely function as sensory organs.
The findings of the study team’s new research show how evolution leads to complex adaptations in specific environments, such as the ability of sea robins to be able to “taste” prey using their quickly scurrying and highly sensitive appendages.
Экологичные материалы в строительстве частных домов — здоровье вашей семьи в приоритете. построить дом
7 simple secrets to eating the Mediterranean way
kraken shop
What if “diet” wasn’t a dirty word?
During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.
“My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”
But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.
“I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.
Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.
Automatic takeoffs are coming for passenger jets and they’re going to redraw the map of the sky
kra9 cc
In late 1965, at what’s now London Heathrow airport, a commercial flight coming from Paris made history by being the first to land automatically.
The plane – A Trident 1C operated by BEA, which would later become British Airways – was equipped with a newly developed extension of the autopilot (a system to help guide the plane’s path without manual control) known as “autoland.”
Today, automatic landing systems are installed on most commercial aircraft and improve the safety of landings in difficult weather or poor visibility.
Now, nearly 60 years later, the world’s third largest aircraft manufacturer, Brazil’s Embraer, is introducing a similar technology, but for takeoffs.
Called “E2 Enhanced Take Off System,” after the family of aircraft it’s designed for, the technology would not only improve safety by reducing pilot workload, but it would also improve range and takeoff weight, allowing the planes that use it to travel farther, according to Embraer.
“The system is better than the pilots,” says Patrice London, principal performance engineer at Embraer, who has worked on the project for over a decade. ”That’s because it performs in the same way all the time. If you do 1,000 takeoffs, you will get 1,000 of exactly the same takeoff.”
Embraer, London adds, has already started flight testing, with the aim to get it approved by aviation authorities in 2025, before introducing it from select airports.
Промокод при регистрации позволит получить подарки – это и бонусное пополнение счета, и бесплатные ставки. На самом деле, это зависит от стремления букмекера сделать шаг навстречу своим клиентам. Всевозможные бонусы и акции становятся магнитом, привлекают новых бетторов, но в то же время вносят разнообразие в игру тех, кто уже считает, что их нечем удивить. Чтобы новый игрок получил на счет приветственный бонус, он должен ввести Melbet промокод в соответствующее поле в регистрационной анкете. Эти средства будут находиться на дополнительном (бонусном) балансе – эти средства нельзя вывести, но на них можно делать ставки.
I conceive this site has some rattling excellent information for everyone : D.
Nice post. I discover something more difficult on diverse blogs everyday. It will always be stimulating to read content off their writers and use a little something at their store. I’d prefer to apply certain with the content in my blog whether you don’t mind. Natually I’ll give you a link for your web weblog. Thanks for sharing.
I still have mixed feelings on the iPad. I’d really like to play around with one to draw a solid conclusion.
проститутки москвы новые проститутки москвы новые .
i like to buy children toys that are educational too, in this way, your kids can learn by playing.,
Получите эксклюзивный cryptoboss casino промокод|Специальное предложение от cryptoboss casino
Бонусный код для cryptoboss casino|Увеличьте свой выигрыш с cryptoboss casino промокодом
Эксклюзивная акция для игроков cryptoboss casino|Секретный код для cryptoboss casino
cryptoboss casino промокод – ваш ключ к выигрышу|cryptoboss casino – играйте со скидкой по промокоду
криптобосс промокод на дополнительные акции hds5 cryptoboss casino промокод бездепозитный .
Играйте в cryptoboss casino с преимуществом промокода
Воспользуйтесь промокодом в cryptoboss casino для дополнительных выигрышей
Играйте в cryptoboss casino с дополнительными бонусами от промокодов|Эксклюзивный cryptoboss casino промокод – ваш шанс на победу
cryptoboss casino – ваш ключ к успеху с промокодом|cryptoboss casino промокод – ваш путь к большим выигрышам|Бонусная программа cryptoboss casino с уникальным промокодом|Играйте с выгодой: cryptoboss casino промокод|Увеличьте свои шансы на победу с cryptoboss casino промокодом|cryptoboss casino – играйте с преимуществами промокода|Играйте в cryptoboss casino с уникальным промокодом и выиграйте больше|Используйте промокод в cryptoboss casino для больших побед|Играйте в cryptoboss casino с преимуществом промокода|Бонусная программа cryptoboss casino с уникальными промокодами|Получите уникальные бонусы с cryptoboss casino промокодом|cryptoboss casino – ваш шанс на успех с промокодом|Уникальное предложение от cryptoboss casino с промокодом|cryptoboss casino – ваш путь к успеху с промокодом|Получите дополнительные бонусы в cryptoboss casino с промокодом|cryptoboss casino – ваш ключ к успеху с промокодами|Играйте в cryptoboss casino с дополнительными преимуществами промокода|Играйте в cryptoboss casino с уникальным промокодом для успеха
ткань от производителя https://kupit-tkan-v-moskve.su/
Профессиональный сервисный центр по ремонту планшетов в том числе Apple iPad.
Мы предлагаем: ремонт планшетов на дому
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Don’t Buy Into These “Trends” Concerning Assessing Adhd In Adults assessment
adhd – Arlie,
купить ткань в москве https://kupit-tkan-v-moskve.su/
Профессиональный сервисный центр по ремонту гироскутеров в Москве.
Мы предлагаем: цены на ремонт гироскутеров
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту моноблоков в Москве.
Мы предлагаем: моноблоки недорого
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
проверенные проститутки в москве проверенные проститутки в москве .
Профессиональный сервисный центр по ремонту гироскутеров в Москве.
Мы предлагаем: где починить гироскутер в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту моноблоков в Москве.
Мы предлагаем: сервис ремонт моноблоков
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту кондиционеров в Москве.
Мы предлагаем: ремонт кондиционера в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Очистить квартиру от гари после пожара https://ubiraem-posle-pozhara-moskva.ru/
ed drugs online from canada: Online medication home delivery – my canadian pharmacy review
Временная регистрация в СПб: Быстро и Легально!
Ищете, где оформить временную регистрацию в Санкт-Петербурге?
Мы гарантируем быстрое и легальное оформление без очередей и лишних документов.
Ваше спокойствие – наша забота!
Минимум усилий • Максимум удобства • Полная легальность
Свяжитесь с нами прямо сейчас!
Временная регистрация
Look of the Week: Forget the naked dress, Kendall Jenner makes the case for underwear as outerwear
kraken войти
On Monday, Kendall Jenner stepped out onto the L’Oreal Paris womenswear runway in a scarlet red Mugler gown that might have looked familiar to anyone with a sharp memory of 1999.
The front of the dress was slashed open across Jenner’s right shoulder, exposing a matching denier bra. The peekaboo moment conjured up memories of another example of fashionable flashing: Lil’ Kim’s purple embellished jumpsuit at the VMAs 26 years earlier. On the red carpet, Kim’s left breast was almost entirely revealed by an asymmetrical cut — a mirror image of Jenner’s neckline — save for a matching purple nipple pasty.
Jenner’s Mugler moment was just the latest example of a resurging tendency for underwear as outerwear. At the Nensi Dojaka runway show in London earlier this month, boxy blazers were shrugged over strappy bras while paneled bustiers in sheer fabric were paired with capri trousers and reimagined as going out tops. Brasseries were even left exposed to the elements at Erdem — a departure for a house beloved by both British acting royalty (Kristen Scott Thomas) and actual royalty (the Duchess of Cambridge). Dolce & Gabbana got the memo, too, showing satin corsets, garter belts and Madonna-esque cone bras at Milan Fashion Week on Saturday. Florence Pugh even wore one of the label’s risque designs in her first British Vogue cover last week — the circle neckline of her puff-shouldered black dress scooping just above the belly button, acting as a full-frontal frame for her bra.
But the trend extends beyond just the runways. During the first performance of her “Short n’ Sweet” tour on Monday, singer Sabrina Carpenter took to the stage in a custom Victoria’s Secret bodysuit and stockings. Hand-adorned with over 150,000 crystals, the strapless pink lace-trimmed leotard took over 140 hours to make. On Monday,YouTube star and singer Jojo Siwa inverted the fad by donning a codpiece for a headline-grabbing cover shoot with LadyGunn magazine. The 15th century undergarment was bedazzled with flesh-colored gemstones.
{Tôi đã cực kỳ hài lòng khám phá trang web này. Tôi muốn cảm ơn bạn {vì đã|dành thời gian cho|chỉ vì điều này|vì điều này|cho bài đọc tuyệt vời này!! Tôi chắc chắn thực sự thích từng một chút nó và tôi cũng đã đã lưu vào mục ưa thích để xem điều mới trên trang web của bạn.|Tôi có thể chỉ nói rằng thật thoải mái để khám phá một người mà thực sự biết họ là gì đang nói về trên internet. Bạn chắc chắn biết cách đưa một rắc rối ra ánh sáng và làm cho nó trở nên quan trọng. Nhiều người hơn phải xem điều này và hiểu khía cạnh này câu chuyện của bạn. Tôi không thể tin bạn không nổi tiếng hơn vì bạn chắc chắn sở hữu món quà.|Rất hay bài viết trên blog. Tôi hoàn toàn đánh giá cao trang web này. Tiếp tục với nó!|Thật khó tìm những người có hiểu biết sâu rộng trong chủ đề cụ thể này, tuy nhiên, bạn nghe có vẻ bạn biết mình đang nói gì! Cảm ơn|Bạn nên tham gia một cuộc thi dành cho một trang web trên mạng tốt nhất. Tôi sẽ khuyến nghị blog này!|Một hấp dẫn đáng giá bình luận. Tôi nghĩ rằng bạn nên viết thêm về vấn đề này, nó có thể không là một điều cấm kỵ chủ đề nhưng điển hình mọi người không nói về những chủ đề như vậy. Đến phần tiếp theo! Trân trọng.|Chào buổi sáng! Tôi chỉ muốn cho bạn một rất to cho thông tin tuyệt vời bạn có ở đây trên bài đăng này. Tôi sẽ là trở lại trang web của bạn để biết thêm thông tin sớm nhất.|Khi tôi ban đầu để lại bình luận tôi có vẻ như đã nhấp hộp kiểm -Thông báo cho tôi khi có bình luận mới- và từ bây giờ mỗi lần được thêm vào tôi nhận được 4 email có cùng nội dung. Có một phương pháp dễ dàng bạn có thể xóa tôi khỏi dịch vụ đó không? Kudos.|Lần sau nữa Tôi đọc một blog, Hy vọng rằng nó không làm tôi thất vọng nhiều như bài này. Rốt cuộc, Tôi biết điều đó là sự lựa chọn của tôi để đọc hết, tuy nhiên tôi thực sự nghĩ bạn sẽ có điều gì đó hữu ích để nói. Tất cả những gì tôi nghe được là một loạt khóc lóc về điều gì đó mà bạn có thể sửa nếu bạn không quá bận tìm kiếm sự chú ý.|Đúng với bài viết này, tôi nghiêm túc nghĩ trang web này cần nhiều hơn nữa sự chú ý.
Получите эксклюзивный cryptoboss casino промокод|Новый промокод для cryptoboss casino
Играйте в cryptoboss casino с привлекательным промокодом|Увеличьте свой выигрыш с cryptoboss casino промокодом
Эксклюзивная акция для игроков cryptoboss casino|Играйте в cryptoboss casino с бонусным кодом
cryptoboss casino промокод – ваш ключ к выигрышу|Бонус при регистрации в cryptoboss casino с промокодом
cryptoboss casino промокод бездепозитный cryptoboss ru casino криптобосс промокод на бонус при регистрации .
Играйте в cryptoboss casino с преимуществом промокода
Получите бонусный приз с cryptoboss casino промокодом
Увеличьте свои шансы на победу с cryptoboss casino промокодами|Получите уникальное предложение с cryptoboss casino промокодами
Успейте воспользоваться cryptoboss casino промокодом и выиграть больше|cryptoboss casino – ваши шансы на победу с промокодами|cryptoboss casino промокод – ваш путь к успеху|Получите привилегии в cryptoboss casino с промокодом|Получите уникальные бонусы в cryptoboss casino по промокоду|Бонусы и привилегии с cryptoboss casino промокодом|Получите дополнительные бонусы с cryptoboss casino промокодом|Уникальное предложение для игроков cryptoboss casino: промокод|Специальные бонусы с cryptoboss casino промокодом|cryptoboss casino промокоды – ваш путь к успеху|Получите уникальные бонусы с cryptoboss casino промокодом|cryptoboss casino промокод – ваш ключ к победе|Играйте в cryptoboss casino с дополнительными бонусами по промокоду|Играйте в cryptoboss casino с уникальными привилегиями по промокоду|Используйте cryptoboss casino промокод для увеличения шансов на победу|cryptoboss casino – ваш ключ к успеху с промокодами|Увеличьте свои шансы на победу в cryptoboss casino с промокодом|Получите дополнительные бонусы в crypt
Look of the Week: Forget the naked dress, Kendall Jenner makes the case for underwear as outerwear
kra8 сс
On Monday, Kendall Jenner stepped out onto the L’Oreal Paris womenswear runway in a scarlet red Mugler gown that might have looked familiar to anyone with a sharp memory of 1999.
The front of the dress was slashed open across Jenner’s right shoulder, exposing a matching denier bra. The peekaboo moment conjured up memories of another example of fashionable flashing: Lil’ Kim’s purple embellished jumpsuit at the VMAs 26 years earlier. On the red carpet, Kim’s left breast was almost entirely revealed by an asymmetrical cut — a mirror image of Jenner’s neckline — save for a matching purple nipple pasty.
Jenner’s Mugler moment was just the latest example of a resurging tendency for underwear as outerwear. At the Nensi Dojaka runway show in London earlier this month, boxy blazers were shrugged over strappy bras while paneled bustiers in sheer fabric were paired with capri trousers and reimagined as going out tops. Brasseries were even left exposed to the elements at Erdem — a departure for a house beloved by both British acting royalty (Kristen Scott Thomas) and actual royalty (the Duchess of Cambridge). Dolce & Gabbana got the memo, too, showing satin corsets, garter belts and Madonna-esque cone bras at Milan Fashion Week on Saturday. Florence Pugh even wore one of the label’s risque designs in her first British Vogue cover last week — the circle neckline of her puff-shouldered black dress scooping just above the belly button, acting as a full-frontal frame for her bra.
But the trend extends beyond just the runways. During the first performance of her “Short n’ Sweet” tour on Monday, singer Sabrina Carpenter took to the stage in a custom Victoria’s Secret bodysuit and stockings. Hand-adorned with over 150,000 crystals, the strapless pink lace-trimmed leotard took over 140 hours to make. On Monday,YouTube star and singer Jojo Siwa inverted the fad by donning a codpiece for a headline-grabbing cover shoot with LadyGunn magazine. The 15th century undergarment was bedazzled with flesh-colored gemstones.
купить ткань в магазине https://kupit-tkan-optom.ru/