Nima uchun bu mag'lubiyatni ajratuvchi funktsiya ishlamaydi?

Men bo'shliqlarni mag'lubiyatdan o'chirib tashlash va strings uzunligini bo'sh joylar bilan qaytarish uchun funksiya yaratdim, biroq funksiya faqat bo'shliqlarni yo'qotadi. Bundan tashqari, ushbu funktsiyani to'g'rilash mumkinligini nazarda tutib, buni amalga oshirishning eng yaxshi usuli mavjud.

let string="This string is going to lose characters";

function charLength(str){
    let strArray=str.split("");
    let output="";

    for(let i=0; i < strArray.length; i++){
        if(strArray[i]===" "){
            strArray.splice(strArray[i],1);
        }
        else{
            output+=strArray[i];
        }
    }
    return output.length//+ " " output, if I were to add this you would see its deleting characters
}

charLength(string);//returns "27 Thistringsoingooseharacters", not "33 Thisstringisgoingtolosecharacters"
0
Javascript tarbiyachi da sizning funktsiyangizni sinab ko'rsangiz, ba'zi belgilar yo'qolib qolishining sababi aniq bo'ladi >. splice qanday qilib ko'chadan ichidagi qatorni aylantirishi va shuning uchun indeks qiymatini o'zgartiradigan jonli ko'rasiz.
qo'shib qo'ydi muallif Ettore Rizza, manba

7 javoblar

Belgilarning yo'qolishining sababi, ro'yxat loop ichida o'zgartirilganligi.

for(let i=0; i < strArray.length; i++){
    if(strArray[i]===" "){
        strArray.splice(strArray[i],1); //Items are removed here
    ...

Agar i belgisini olib tashlasangiz, keyingi belgilar o'rnini oladi.

Buning o'rniga, replace funksiyasidan foydalanishingiz mumkin:

string.replace(/ /gi, "").length
2
qo'shib qo'ydi

Agar belgini magistraldan olib tashlasangiz, ( i - ) bir qadam orqaga qaytib ketishingiz kerak, loop bir belgini ( for (...; i ++) ). Shunga o'xshash:

if (strArray[i] === " ") {
  strArray.splice(strArray[i], 1);
  i--;//ge back one step if we remove one character.
}

Parchalash:

<div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden">

let string = "This string is not going to lose characters";

function charLength(str) {
  let strArray = str.split("");
  let output = "";

  for (let i = 0; i < strArray.length; i++) {
    if (strArray[i] === " ") {
      strArray.splice(strArray[i], 1);
      i--;
    } else {
      output += strArray[i];
    }
  }
  return output;
}

console.log(charLength(string));
</div> </div>

Bo'sh bo'lmagan belgilarni hisoblashni istasangiz:

Shunday qilib, bunday bo'shliq bo'lmagan belgilarni hisoblash uchun taymerni tanlang:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

let string = "This string is not going to lose characters";

function charLength(str) {
  let counter = 0;                       //the counter
  for (let i = 0; i < str.length; i++) { //for each character in the string
    if(str.charAt(i) !== ' ')            //if the character is not a space
      counter++;                         //increment the counter
  }
  return counter;
}

console.log(charLength(string));
</div> </div>
2
qo'shib qo'ydi

Eritrni filtrlash uchun muntazam ifoda ishlatishingiz mumkin

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var string = "This string is going to lose characters",
    result = [...string].filter(RegExp.prototype.test.bind(RegExp('[^ ]'))).join('');

console.log(result);
console.log(result.length);
</div> </div>

Yoki bo'sh joyni sinab ko'ring.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var string = "This string is going to lose characters",
    result = [...string].filter(a => a !== ' ').join('');

console.log(result);
console.log(result.length);
</div> </div>
1
qo'shib qo'ydi

Bu siz qilganingizdan ko'ra osonroq. .replace() mag'lubiyat uslubini o'zgartirishi mumkin.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

function charLength(str){

   //Create a new string that is the same as the passed in one, but with the spaces stripped out
   //The syntax// denotes a regular expresion (regEx) object 
   //The s+ denotes to look for one or more spaces in a row
   //The g denotes a global search and replace througout the string 
    var newStr = str.replace(/\s+/g, "");

    console.log("\"" + str + "\" has: " + str.length + " characters."); 
    console.log("\"" + newStr + "\" has: " + newStr.length + " characters."); 
}

charLength("This string is going to lose characters");
</div> </div>
1
qo'shib qo'ydi

Ushbu yo'nalish o'rniga bu erda:

strArray.splice (strArray [i], 1);

Buni ishlatib ko'ring:

strArray.splice (strArray [i], 0);

Just replaces the 1 with 0

1
qo'shib qo'ydi

Regexdan foydalaning.

var str = 'This string is going to lose characters';

// The substituted value will be contained in the result variable
const result = str.replace(/\s/g, '');

console.log('Substitution result: ', result.length);
1
qo'shib qo'ydi

Siz regeksga ehtiyoj sezmaysiz: str.replace ("", "") allaqachon buni qilmoqda.

1
qo'shib qo'ydi
Javascript UZB
Javascript UZB
99 ishtirokchilar

@js_uzb @vuejs_uz @react_uz @nodejs_uz @angular_uz @ngTashkent @yiiframework_uz @laravel_uz @linux_uzbek @python_uz @swift_uzb —————— @uzdevgroup @UzGeeksGroup ——— @UzDev_Jobs @jobs_uzb