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); //排序後:法国话,京片子,英语,中国,中文
LOS ANGELES, Jan 12 (Reuters) – Firefighters were slowly
[url=https://kraken5af44k24fwzohe6fvqfgxfsee4lgydb3ayzkfhlzqhuwlo3ad.com]kraken5af44k24fwzohe6fvqfgxfsee4lgydb3ayzkfhlzqhuwlo33ad[/url] making progress in their battle to contain the inferno that has razed swathes of Los Angeles’ Pacific Palisades neighborhood to the ground, but still-spreading flames threatened communities in the populous San Fernando Valley on Sunday.
Aircraft dropped water and fire retardant on steep hills to stem the eastward spread of the Palisades Fire and KTLA television reported that ground crews had managed to save a number of houses, although others were lost.
kraken5af44k24fwzohe6fvqfgxfsee4lgydb3ayzkfhlzqhuwlo33ad.onion
https://kraken5af44k24fwzohe6fvqfgxfsee4lgydb3ayzkfhlzqhuwlo33adonion.info
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали ремонт кофемашин philips рядом, можете посмотреть на сайте: срочный ремонт кофемашин philips
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Aerodrome Finance: Unlocking Potential for Growth
The world of aerodrome finance is pivotal for ensuring the efficient operation, enhancement, and expansion of aerodrome facilities globally. With the increasing demand for air travel, understanding aerodrome financial processes is more important than ever.
[url=https://aerlifi.org/]aerodrome finance[/url]
Why Aerodrome Finance Matters
Aerodrome finance plays a critical role in the lifespan of airport projects, providing necessary funding from initial development to ongoing management. Here are key reasons why it matters:
Infrastructure Development: Secure financial backing enables the construction and maintenance of essential airport infrastructure.
Operational Efficiency: Adequate funding ensures that airports can operate smoothly, adapting to technological advancements and logistical demands.
Economic Growth: Airports serve as economic hubs; their development stimulates job creation and boosts local economies.
Aerodrome Finance Strategies
Various strategies can be employed to optimize aerodrome finance, ensuring both immediate and long-term benefits. Here are a few notable approaches:
Public-Private Partnerships (PPP)
These partnerships combine public sector oversight and private sector efficiency, leading to shared risks and rewards. They facilitate diverse financial resources and innovative solutions for airport projects.
Revenue Diversification
Exploring non-aeronautical revenue streams, such as retail concessions and property leases, can significantly bolster an airport’s financial resilience. Such diversification allows for a steady income flow independent of ticket sales.
Sustainable Financing
Adopting sustainable financial practices, including green bonds and ESG (Environmental, Social, and Governance) criteria, aligns with modern ecological standards and attracts environmentally conscious investors.
Challenges and Opportunities
While aerodrome finance offers numerous benefits, it also poses certain challenges. High capital costs, regulatory hurdles, and fluctuating passenger demands can impact financial stability. However, these challenges also present opportunities for innovation and improvement.
Tech-Driven Solutions: Embracing technology like AI and predictive analytics can enhance decision-making and financial planning.
Collaboration: Strengthening ties with stakeholders, including airlines and government agencies, can streamline financial operations and capital investments.
Ultimately, the goal of aerodrome finance is to support the sustainable growth and modernization of airports, ensuring their pivotal role in global connectivity remains strong.
isotretinoin 40mg without prescription – order zyvox 600 mg online cheap generic linezolid 600mg
Официальная покупка школьного аттестата с упрощенным обучением в Москве
Base Bridge: Your Gateway to Seamless Asset Transfer
As the digital landscape expands, transferring assets across different blockchain networks has become increasingly important. Base Bridge offers a robust solution for managing digital assets efficiently and securely.
[url=https://bsblifi.net]base bridge[/url]
What is Base Bridge?
Base Bridge is a cutting-edge platform designed to facilitate the seamless transfer of assets between different blockchain networks. By providing a bridge across these networks, users can enjoy enhanced connectivity and flexibility.
Key Features of Base Bridge
Interoperability: Connects multiple blockchain networks for seamless asset transfers.
Security: Ensures secure transactions with state-of-the-art encryption.
Speed: Fast transactions ensure access to funds without delays.
Benefits of Using Base Bridge
Whether you’re a developer, investor, or enthusiast, Base Bridge offers numerous benefits including:
Reduced Costs: Minimize fees associated with cross-chain transactions.
Broader Access: Gain access to a wider array of assets and networks.
User-Friendly Experience: Intuitive interface that caters to both novice and advanced users.
How to Get Started with Base Bridge
Embarking on your Base Bridge journey is straightforward:
Sign up on the .
Connect your digital wallet.
Choose the networks and assets you wish to transfer.
Execute transactions quickly and securely.
Base Bridge stands as a pillar in the future of digital asset management, paving the way for a more interconnected blockchain ecosystem. By leveraging Base Bridge, users can confidently navigate the complexities of digital asset exchanges.
Visit today to explore the full potential of your digital assets.
Phantom Wallet
Phantom Wallet offers secure storage for your crypto assets with a user-friendly interface. Get started and protect your investments today.
phantom wallet extension download
Why Choose Phantom Wallet for Your Cryptocurrency?
In the ever-evolving world of cryptocurrency, securing your digital assets is paramount. With numerous wallets available, choosing the right one can be daunting. Here’s why Phantom Wallet stands out:
User-Friendly Interface
Phantom Wallet is designed for both beginners and experienced traders. Its intuitive layout ensures easy navigation, making it simple to manage your digital assets efficiently.
Comprehensive Security Features
Your safety is a priority. Phantom Wallet employs state-of-the-art encryption and security protocols to protect your cryptocurrencies from unauthorized access.
Multi-Platform Accessibility
Access your wallet from multiple devices with ease. Phantom supports various operating systems, offering flexibility and convenience for all users.
Real-time Updates
Stay informed with instant notifications about your transactions and wallet activities. You can monitor your assets and market trends effortlessly.
Setting Up Phantom Wallet
Download the Phantom Wallet from the official website.
Create a secure password and back up your recovery phrase.
Start managing your cryptocurrencies seamlessly.
Advantages of Phantom Wallet
Fast Transactions: Experience lightning-fast transaction speeds, ensuring your trades are completed in seconds.
Low Fees: Benefit from competitive transaction fees, maximizing your returns.
Comprehensive Support: Access 24/7 customer support to assist you with any inquiries or issues.
Embrace the future of digital finance with . Secure, user-friendly, and reliable—it’s the smart choice for anyone serious about managing their cryptocurrency securely and effectively.
диплом о полном среднем образовании купить
купить в вологде диплом
Haven’t discovered what you are looking for?
рейтинг процессоров intel http://www.topcpu.ru/ .
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали ремонт кофемашин melitta рядом, можете посмотреть на сайте: ремонт кофемашин melitta рядом
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
вывести из запоя анонимно вывести из запоя анонимно .
вывод из запоя на дому в ростове вывод из запоя на дому в ростове .
капельница от запоя ростов на дону [url=http://vyvod-iz-zapoya-rostov222.ru]капельница от запоя ростов на дону[/url] .
вывод из запоя в стационаре ростов [url=https://vyvod-iz-zapoya-rostov239.ru/]https://vyvod-iz-zapoya-rostov239.ru/[/url] .
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали ремонт кофемашин neff в москве, можете посмотреть на сайте: ремонт кофемашин neff сервис
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
сравнение производительности процессоров topcpu.ru .
вывод из запоя круглосуточно ростов на дону вывод из запоя круглосуточно ростов на дону .
вывод из запоя в ростове-на-дону вывод из запоя в ростове-на-дону .
капельница от запоя на дому капельница от запоя на дому .
вывод. из. запоя. на. дому. ростов. https://vyvod-iz-zapoya-rostov239.ru/ .
https://maxpillsformen.com/# Cialis 20mg price
Cialis without a doctor prescription Generic Cialis without a doctor prescription Cialis 20mg price in USA
вывод из запоя в ростове вывод из запоя в ростове .
вывод из запоя дешево ростов на дону https://vyvod-iz-zapoya-rostov222.ru .
рейтинги производительности процессоров [url=topcpu.ru]рейтинги производительности процессоров[/url] .
вывод из запоя ростов-на-дону вывод из запоя ростов-на-дону .
нарколог на дом вывод из запоя ростов нарколог на дом вывод из запоя ростов .
Приобретение школьного аттестата с официальным упрощенным обучением в Москве