Ошибка javascript строка не функция

You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.

In that case, you end up with very much simpler functions:

function validateLetters(s) {
  return /^[a-z]+$/i.test(s);
}

function validateNumbers(s) {
  return /^d+$/.test(s);
}

To validate an input, you can add a class to say what type of validation it should have, e.g.

<input name="letter3" class="letter" onkeypress="validateLetter(this)">

Then the validateInput function can determine which validation function to call based on the class:

function validateInput(element) {

  var value = element.value;

  // If has class letter, validate is only letters
  if (/(s|^)letter(s|$)/i.test(element.className)) {

    // validate only if there is a value other than empty string
    if (!validateLetters(value) && value != '') {
      alert('Please enter only letters');
    }
  }

  // If has class number, validate is only numbers
  if (/(s|^)number(s|$)/i.test(element.className)) {

    // validate only if there is a value other than empty string
    if (!validateNumbers(element.value) && value != '') {
      alert('Please enter only numbers');
    }
  }
}

Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn’t see the value resulting from the keypress, it sees the previous value.

You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O’Reilly).

Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:

<form>
  <p>Enter your mother's maiden name:
    <input name="letter1" class="letter" onkeypress="validateInput(this)">
  </p>
  <p>Enter the number of siblings you have:
    <input name="number3" class="number" onkeypress="validateInput(this)">
  </p>
  <p>
    <input type="reset">
  </p>
</form>

I don’t understand why I get an error message using the substring method to declare a variable.

I want to use the first part of the URL in a comparison.

Site: http://www.elizabet.nl/wordpress

This is the part that’s going wrong:

var currentLocation = document.location,
muzLoc = currentLocation.substring(0,45),
prodLoc = currentLocation.substring(0,48), 
techLoc = currentLocation.substring(0,47); 

The error:
«currentLocation.substring is not a function»

But this part of the code is fine:

var URL = $(this).attr("href").substring(2) + ' #main';

All of the code:

jQuery(function($){

    var siteURL = "http://" + top.location.host.toString() + "/wordpress", // Declareren van URL van de website.
        URL = '', // Declareren van een URL, welke dan ook. 
        currentLocation = '',
        muzLoc = '',
        prodLoc = '',
        techLoc = '',               
        allLinks = $('a[href^=' + siteURL + ']' ), // Declareren van alle menu-links. Het teken ^ betekent 'begint met'.
        otherLinks = $('a[href^=' + siteURL + "/wp-content" + ']'), 
        siteLinks = $(allLinks).not(otherLinks),      
        mainDiv = $("#content"),
        hash = window.location.hash,
        muziekURL = "http://www.elizabet.nl/wordpress/#/muziek_pf/",
        productieURL = "http://www.elizabet.nl/wordpress/#/productie_pf/",
        techniekURL = "http://www.elizabet.nl/wordpress/#/techniek_pf/";    

    if (hash) {
        hash = "/wordpress" + hash.substring(1); // substring methode haalt karakters van je string af. In dit geval de #, vanwege de offset=1.
        URL = hash;
        $(mainDiv).load(URL);           
    }

function pageLoad() {

                var allLinks = $('a[href^=' + siteURL + ']' ),
                otherLinks = $('a[href^=' + siteURL + "/wp-content" + ']'), 
                siteLinks = $(allLinks).not(otherLinks); 

                siteLinks.each(function() {             

                    $(this).attr("href", "#" + this.pathname.substring(10));
                    })

                    .click(function() {
                    var URL = $(this).attr("href").substring(2) + ' #main';
                    $(mainDiv).load(URL, function(){ 

                    var currentLocation = document.location,
                        muzLoc = currentLocation.substring(0,45),
                        prodLoc = currentLocation.substring(0,48), 
                        techLoc = currentLocation.substring(0,47);                  

                if (muzLoc == muziekURL) {              
                $("body").animate({ backgroundColor: "#151C07"}, 500);
                $(".nieuws").animate({ borderBottomColor: "#99CC33"}, 500);  
                $("#stripe_trans").add("#header").animate({ backgroundColor: "#99CC33"}, 500);
                $("#tabtekst_3").stop().animate({ backgroundColor: "#B8860B" }, 500);
                $("#tab_3").add("a.gold").stop().animate({ color: "#B8860B" }, 500);
                $("#tabtekst_4").stop().animate({ backgroundColor: "#765AAD" }, 500);  
                $("#tab_4").add("a.purple").stop().animate({ color: "#765AAD" }, 500);                                    
                }

                else if (prodLoc == productieURL) {     
                $("body").animate({ backgroundColor: "#251B02"}, 500);  
                $(".nieuws").animate({ borderBottomColor: "#FFCC33"}, 500);  
                $("#stripe_trans").add("#header").animate({ backgroundColor: "#FFCC33"}, 500);                  
                $("#tabtekst_2").stop().animate({ backgroundColor: "#6B8E23" }, 500);  
                $("#tab_2").add("a.green").stop().animate({ color: "#6B8E23" }, 500);   
                $("#tabtekst_4").stop().animate({ backgroundColor: "#765AAD" }, 500);  
                $("#tab_4").add("a.purple").stop().animate({ color: "#765AAD" }, 500);
                } 

                else if (techLoc == techniekURL) {      
                $("body").animate({ backgroundColor: "#181223"}, 500);  
                $(".nieuws").animate({ borderBottomColor: "#B39BE4"}, 500);  
                $("#stripe_trans").add("#header").animate({ backgroundColor: "#B39BE4"}, 500);          
                $("#tabtekst_2").stop().animate({ backgroundColor: "#6B8E23" }, 500);  
                $("#tab_2").add("a.green").stop().animate({ color: "#6B8E23" }, 500);                       
                $("#tabtekst_3").stop().animate({ backgroundColor: "#B8860B" }, 500);
                $("#tab_3").add("a.gold").stop().animate({ color: "#B8860B" }, 500);
                } 

                else {
                $("body").animate({ backgroundColor: "#202020"}, 500);  
                $(".nieuws").animate({ borderBottomColor: "#FFF"}, 500);  
                $("#stripe_trans").add("#header").animate({ backgroundColor: "#FFF"}, 500);             
                $("#tabtekst_2").stop().animate({ backgroundColor: "#6B8E23" }, 500);  
                $("#tab_2").add("a.green").stop().animate({ color: "#6B8E23" }, 500);               
                $("#tabtekst_3").stop().animate({ backgroundColor: "#B8860B" }, 500);
                $("#tab_3").add("a.gold").stop().animate({ color: "#B8860B" }, 500);
                $("#tabtekst_4").stop().animate({ backgroundColor: "#765AAD" }, 500);  
                $("#tab_4").add("a.purple").stop().animate({ color: "#765AAD" }, 500);                                          
                }

                pageLoad();
            });             
        });
}

pageLoad();


}); // End document ready function.

TypeError:»x» не является функцией

Исключение JavaScript «не является функцией» возникает,когда была попытка вызвать значение из функции,но на самом деле значение не является функцией.

Message

TypeError: "x" is not a function. (V8-based & Firefox & Safari)

Error type

Что пошло не так?

Она пыталась вызвать значение из функции,но на самом деле значение не является функцией.Какой-то код ожидает,что вы предоставите функцию,но этого не произошло.

Может, в названии функции опечатка? Может быть, объект, для которого вы вызываете метод, не имеет этой функции? Например, у Objects JavaScript нет функции map , но у объекта Array JavaScript есть.

Существует множество встроенных функций,нуждающихся в функции (обратного вызова).Чтобы эти методы работали должным образом,вам необходимо предоставить функцию:

  • При работе с объектами Array или TypedArray :
    • Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), Array.prototype.reduceRight(), Array.prototype.find()
  • При работе с объектами Map и Set :
    • Map.prototype.forEach() и Set.prototype.forEach()

Examples

Ошибка в названии функции

В этом случае,что случается слишком часто,в названии метода присутствует опечатка:

const x = document.getElementByID('foo');

Правильное имя функции — getElementById :

const x = document.getElementById('foo');

Функция вызвана не на том объекте

Для определенных методов вы должны предоставить функцию (обратного вызова), и она будет работать только с определенными объектами. В этом примере используется Array.prototype.map() , который работает только с объектами Array .

const obj = { a: 13, b: 37, c: 42 };

obj.map(function (num) {
  return num * 2;
});


Вместо этого используйте массив:

const numbers = [1, 4, 9];

numbers.map(function (num) {
  return num * 2;
});


Функция разделяет имя с ранее существовавшей собственностью

Иногда при создании класса может быть свойство и функция с тем же именем.При вызове функции компилятор думает,что функция перестает существовать.

function Dog() {
  this.age = 11;
  this.color = "black";
  this.name = "Ralph";
  return this;
}

Dog.prototype.name = function (name) {
  this.name = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Вместо этого используйте другое имя свойства:

function Dog() {
  this.age = 11;
  this.color = "black";
  this.dogName = "Ralph"; 
  return this;
}

Dog.prototype.name = function (name) {
  this.dogName = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Использование скобок для умножения

В математике 2 × (3+5)можно записать как 2*(3+5)или просто 2(3+5).

Использование последнего приведет к ошибке:

const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);

Вы можете исправить код, добавив оператор * :

const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);

Правильно импортируйте экспортированный модуль

Убедитесь,что вы правильно импортируете модуль.

Пример библиотеки помощников ( helpers.js )

const helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    acc[key] ??= [];
    acc[key].push(obj);
    return acc;
  }, {});
}

export default helpers;

Правильное использование импорта ( App.js ):

import helpers from './helpers';

See also

  • Functions


JavaScript

  • RangeError:аргумент не является корректной кодовой точкой

    Исключение JavaScript «Недопустимая кодовая точка» возникает, когда значения NaN, отрицательные целые числа (-1), нецелые числа (5.4) или больше 0x10FFFF (1114111)

  • TypeError: «x» не является конструктором

    Исключение JavaScript «не является конструктором» возникает, когда была попытка использовать объектную переменную, но была попытка использовать объект или переменную

  • ReferenceError: «x» не определен

    Исключение JavaScript «переменная не определена» возникает, когда где-то есть несуществующая ссылка.

  • RangeError:точность вне досягаемости

    Исключение JavaScript «точность вне допустимого диапазона» возникает, когда число, выходящее за пределы 0 и 20 (или 21), было передано в toFixed toPrecision.

Table of Contents

Hide

  1. What is TypeError: split is not a function error?
  2. How to fix TypeError: split is not a function error?
    1. Solution 1: Convert the value into a string
    2. Solution 2 – Performing the type check
  3. Conclusion

If we call the split() method on the value that is not of a string type, JavaScript will throw a TypeError: split is not a function.

In this tutorial, we will look at what is TypeErrror: split is not a function error and how to resolve them with examples.

Let us take a simple example to demonstrate this issue

// documnet.location returns an object
const str = document.location
path = str.split("/")

Output

TypeError: str.split is not a function

In the above example, we have declared a variable and assigned the object into it.

In the next statement, we call the String.split() method on the location object, and hence we get a TypeError: split is not a function.

We can also check the variable type using typeof() to confirm the datatype.

const str = document.location
console.log("The type of variable is",typeof(str))

Output

The type of variable is object

How to fix TypeError: split is not a function error?

The String.split() method can only be used on the string values and not on any other types. 

There are two ways to fix this issue in JavaScript.

Solution 1: Convert the value into a string

We can easily resolve the issue by converting the location object into a string before calling the split() method.

If we know the value can be converted to a valid string, then we can use the toString() method in JavaScript that returns the string representing the object. 

Let us take an example to resolve the issue using the toString() method.

// Get the location and convert to String object
const str = document.location.toString()
console.log(str)
console.log("The object type is", typeof(str))

// Split the string object into an Array
path = str.split("/")
console.log(path)

Output

https://itsjavascript.com/javascript-typeerror-string-split-is-not-a-function

The object type is string

['https:', '', 'itsjavascript.com', 'javascript-typeerror-string-split-is-not-a-function']

Solution 2 – Performing the type check

We can also perform a type check on the variable to check if it’s a string before calling the split() method.

Example – Type check using if/else

// Get the location and convert to String object
const str = document.location.toString()

//Split the string object into an Array
if (typeof str === 'string') {
    path = str.split("/")
    console.log(path)
}
else {
    console.log("Not a vaild string object")
}

Output

['https:', '', 'itsjavascript.com', 'javascript-typeerror-string-split-is-not-a-function']

Example – Type check using ternary operator

const str = document.location.toString()
const result = typeof str === 'string' ? str.split('/') : "";
console.log(result)

Output

['https:', '', 'itsjavascript.com', 'javascript-typeerror-string-split-is-not-a-function']

Conclusion

The TypeError: split is not a function occurs if we call a split() method on the value that is not of a type string. We can resolve the issue by converting the value into string before calling the split() method or by performing a type check; we can mitigate this error.

Related Tags
  • split(),
  • toString(),
  • TypeError,
  • typeof

Sign Up for Our Newsletters

Get notified on the latest articles

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Debugging «TypeError: X is not a function» in JavaScript

Jul 27, 2020

The TypeError: X is not a function error is a common cause of confusion for JavaScript beginners.
JavaScript throws this error when you attempt to call a value that isn’t a function. For example:

const x = 42;

x(); // Throws 'TypeError: x is not a function'

Most modern JavaScript runtimes are good about formatting this error, so you know what expression you tried to call that isn’t a function. For example, another common cause of
this error is calling a non-existant method on an object.

const moment = require('moment');

const date = moment('2020-06-01');

// Typo! Throws 'TypeError: date.formt is not a function'
date.formt('YYYY-MM-DD');

If JavaScript throws this error in code that you wrote, you should double check the code at the line number
in the error’s stack trace. Odds are, you either typo-ed, or you need to add a check to make sure the value
that you’re calling is a function.

// Ensure that `x` is a function to avoid TypeError.
if (typeof x !== 'function') {
  return;
}

x();

A Note on Semicolons

If you don’t use semicolons, you can get some surprising instances of this error. For example, the below
code throws TypeError: arr[0] is not a function:

const arr = []

const val = arr[0]
(function() { console.log(val) })()

Because there isn’t a semicolon at the end of arr[0], JavaScript treats the above code as equivalent to:

const arr = []

const val = arr[0](function() { console.log(val) })()

If you write JavaScript without semicolons, be sure to use a linter to avoid mistakes like this!


More Fundamentals Tutorials

  • 3 Patterns to Merge Arrays in JavaScript
  • Convert a BigInt to a Number in JavaScript
  • The parseInt Function in JavaScript
  • The toFixed() Function in JavaScript
  • The Nullish Coalescing Operator ?? in JavaScript
  • Implementing Tuples in JavaScript
  • Convert a JavaScript Enum to a String

Понравилась статья? Поделить с друзьями:
  • Ошибка lavenbeard sea of thieves
  • Ошибка javascript не удалось найти java апплет
  • Ошибка java неверный формат samsung
  • Ошибка launcher для gta 5
  • Ошибка javascript не определено не функция