簡體   English   中英

如果在 javascript 中已到達數組的末尾,則從數組的開頭重新啟動

[英]Restart from the beginning of the array if you have reached the end of it in javascript

我的目標是用字母表后面一定數量的位置(在輸入中提供)中找到的字符替換句子的字符。 一種加密。 我的問題是,如果句子中有一個 Z 或某個字符超過了數組的最大大小。 我怎樣才能確保如果有人(例如)寫 Y 並將其移動 3 個字符,則值將是 B?

function criptaFrase(){
var alfabeto = 'abcdefghijklmnopqrstuvwxyz'.split('');
var frase = document.getElementById("frase").value;
var scambia = "";
var posti = parseInt(document.getElementById("posti").value);

for (a = 0; a < frase.length; a++) {
    let b = alfabeto.indexOf(frase.charAt(a));
    b += posti;
    scambia += alfabeto[b];
    document.getElementById("finale").innerHTML = scambia;
}

您可以使用余數運算符 ( % ) 和事物的長度來環繞從 0 開始索引的任何內容。

所以如果是b += posti; 你說的是:

b = (b + posti) % alfabeto.length;

這是該環繞的一個孤立示例:

 const list = ["one", "two", "three", "four"]; let i = 0; for (let counter = 0; counter < 12; ++counter) { console.log(`${i}: ${list[i]}`); i = (i + 1) % list.length; }


(如果你有一些從 1 開始的索引,你可以這樣做: x = x % length + 1; 。但是 JavaScript 數組索引從 0 開始。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM