Posts tagged javascript

Javascript in very short

posted on 2016-04-24 14:23

Well, here is a VERY rough js overview.

embedding

<script language="JavaScript">
    // code...
</script>

variables

Are defined with var keyword: var myvar = 'asdf';

Arrays: (are associative, too)

var myarray = new Array(20);
myarray[15] = 123;
myarray["test"] = 'asdf';

operators

  • == and != (identity checking)
  • && and ||
  • + also contatenates strings

control structures

conditionals:

  • if (...) { ...; } else { ...; }

loops:

  • while (...) { ...; }
  • for (i=0; i<10; i++) { ...; }

objects

  • document = current HTML document where your js stuff is contained within
  • history = list of last used pages, browser does the bookkeeping
  • location = address of curren site
  • navigator = represents the browser
  • window = self-explanatory. Can be used for resizing, alerts and dialogues.

document.write(...) returns stuff. To show the current cookie, which is contained within the document:

document.write(document.cookie)

Try this in the dev console of your browser, which you should get via pressing F12.

Now some often needed methods or properties of the aforementioned objects:

document

methods:

  • close : close document
  • getSelection : return selected text
  • open : open new document

properies:

  • fgColor : foreground color
  • bgColor : background color
  • cookie : create one or show its content
  • alinkColor : color of active link
  • linkColor : color of a link
  • location : get the documents address
  • title ; document's title

window

methods:

  • close : close window
  • home : load browsers home page
  • open : create new window
  • print : open printing dialogue
  • resizeTo : resize window

methods for creating checkboxes and reading user-data without forms:

  • alert : create OK pop-up dialogue box
  • confirm : create YES/NO pop-up dialogue box
  • prompt : shell dialogue, can be read andused by the js code (var xyz = prompt('enter something now');)

properties:

  • defaultStatus : default text shown in browsers status line
  • status : set or show status line text
  • innerHeight : height of the window in pixels where the document can be shown
  • innerWidth : width of the window in pixels where the document can be shown

history

methods:

  • back : go to previous page
  • forward : go to next page

navigator

properties:

  • appName : return browser name
  • appVersion : return browser version
  • language : return browser language
  • platform : return OS

Finally, javascript also has quite some functions for string handling and matching, substrings, dates. But that will be of no further concern here.

Javascript under pressure

posted on 2013-11-10 00:34:10

Somewhere on twitter I stumbled across this link. Since I know almost no javascript, this was a welcome excuse to fuddle around. It took me quite long, like 1,5 hours. I installed a javascript interpreter during that for fun, too. Which is harder than you would imagine, every browser has js built into, but noone seems to need a single executable to use... but Mozilla helped me in the end.

Anyway, my solutions:

First task: Return double value of i.

function doubleInteger(i) {
    return i*2;
}

Easy.

Second task: Return true for even i, else false.

function isNumberEven(i) {
    return !(i % 2);
}

Still easy, though I was not as concise as this at first.

Third task: Return the file extension of a string i, else false.

function getFileExtension(i) {
    return (new RegExp("(\\w*\\.)*\\w*\\.\\w\\w\\w").test(i)) ? i.match("\\w+$") : false;
}

No stranger to regexp's, but never done them in js... Also was not as concise as this at first.

Fourth task: Get the longest string from an array.

function longestString(i) {
    var longString = "";

    for (var x in i)
    {
        var stringToCheck = i[x]; 

        if( Object.prototype.toString.call( i[x] ) === '[object Array]' )
        {
            stringToCheck = longestString( i[x] );
        }

        if (stringToCheck.length > longString.length)
        {
            longString = stringToCheck;
        }
    }
    return longString;
}

Ok, i know i got to use recursion. But what types do I have to check for???

Fifth task: i will be an array, containing integers, strings and/or arrays like itself. Sum all the integers you find, anywhere in the nest of arrays.

function arraySum(i) {

    return i.reduce(
        function(total, i)
        {
            if (typeof i == 'number') 
            {
                return total + i;
            } 
            else if (i.reduce) 
            {
                return total + arraySum(i);
            }
            return total;
        }, 0);
}

So, when this calls itself recursively, and return is found, this is the final return. Counting is stopped, as soon as the first recursive call is finished. Hmmmm. What is this reduce?

Number five I was not able to solve on my own (I blame not knowing any js.). I knew the error cause, but I did not even know what to google beside a complete solution.

This blog covers .csv, .htaccess, .pfx, .vmx, /etc/crypttab, /etc/network/interfaces, /etc/sudoers, /proc, 10.04, 14.04, AS, ASA, ControlPanel, DS1054Z, GPT, HWR, Hyper-V, IPSEC, KVM, LSI, LVM, LXC, MBR, MTU, MegaCli, PHP, PKI, R, RAID, S.M.A.R.T., SNMP, SSD, SSL, TLS, TRIM, VEEAM, VMware, VServer, VirtualBox, Virtuozzo, XenServer, acpi, adaptec, algorithm, ansible, apache, apachebench, apple, arcconf, arch, architecture, areca, arping, asa, asdm, autoconf, awk, backup, bandit, bar, bash, benchmarking, binding, bitrate, blackarmor, blockdev, blowfish, bochs, bond, bonding, booknotes, bootable, bsd, btrfs, buffer, c-states, cache, caching, ccl, centos, certificate, certtool, cgdisk, cheatsheet, chrome, chroot, cisco, clamav, cli, clp, clush, cluster, coleslaw, colorscheme, common lisp, console, container, containers, controller, cron, cryptsetup, csync2, cu, cups, cygwin, d-states, database, date, db2, dcfldd, dcim, dd, debian, debug, debugger, debugging, decimal, desktop, df, dhclient, dhcp, diff, dig, display manager, dm-crypt, dmesg, dmidecode, dns, docker, dos, drivers, dtrace, dtrace4linux, du, dynamictracing, e2fsck, eBPF, ebook, efi, egrep, emacs, encoding, env, error, ess, esx, esxcli, esxi, ethtool, evil, expect, exportfs, factory reset, factory_reset, factoryreset, fail2ban, fbsd, fdisk, fedora, file, filesystem, find, fio, firewall, firmware, fish, flashrom, forensics, free, freebsd, freedos, fritzbox, fsck, fstrim, ftp, ftps, g-states, gentoo, ghostscript, git, git-filter-branch, github, gitolite, global, gnutls, gradle, grep, grml, grub, grub2, guacamole, hardware, haskell, hdd, hdparm, hellowor, hex, hexdump, history, howto, htop, htpasswd, http, httpd, https, i3, icmp, ifenslave, iftop, iis, imagemagick, imap, imaps, init, innoDB, innodb, inodes, intel, ioncube, ios, iostat, ip, iperf, iphone, ipmi, ipmitool, iproute2, ipsec, iptables, ipv6, irc, irssi, iw, iwconfig, iwlist, iwlwifi, jailbreak, jails, java, javascript, javaws, js, juniper, junit, kali, kde, kemp, kernel, keyremap, kill, kpartx, krypton, lacp, lamp, languages, ldap, ldapsearch, less, leviathan, liero, lightning, links, linux, linuxin3months, lisp, list, livedisk, lmctfy, loadbalancing, locale, log, logrotate, looback, loopback, losetup, lsblk, lsi, lsof, lsusb, lsyncd, luks, lvextend, lvm, lvm2, lvreduce, lxc, lxde, macbook, macro, magento, mailclient, mailing, mailq, manpages, markdown, mbr, mdadm, megacli, micro sd, microsoft, minicom, mkfs, mktemp, mod_pagespeed, mod_proxy, modbus, modprobe, mount, mouse, movement, mpstat, multitasking, myISAM, mysql, mysql 5.7, mysql workbench, mysqlcheck, mysqldump, nagios, nas, nat, nc, netfilter, networking, nfs, nginx, nmap, nocaps, nodejs, numberingsystem, numbers, od, onyx, opcode-cache, openVZ, openlierox, openssl, openvpn, openvswitch, openwrt, oracle linux, org-mode, os, oscilloscope, overview, parallel, parameter expansion, parted, partitioning, passwd, patch, pdf, performance, pfsense, php, php7, phpmyadmin, pi, pidgin, pidstat, pins, pkill, plesk, plugin, posix, postfix, postfixadmin, postgres, postgresql, poudriere, powershell, preview, profiling, prompt, proxmox, ps, puppet, pv, pvecm, pvresize, python, qemu, qemu-img, qm, qmrestore, quicklisp, r, racktables, raid, raspberry pi, raspberrypi, raspbian, rbpi, rdp, redhat, redirect, registry, requirements, resize2fs, rewrite, rewrites, rhel, rigol, roccat, routing, rs0485, rs232, rsync, s-states, s_client, samba, sar, sata, sbcl, scite, scp, screen, scripting, seafile, seagate, security, sed, serial, serial port, setup, sftp, sg300, shell, shopware, shortcuts, showmount, signals, slattach, slip, slow-query-log, smbclient, snmpget, snmpwalk, software RAID, software raid, softwareraid, sophos, spacemacs, spam, specification, speedport, spi, sqlite, squid, ssd, ssh, ssh-add, sshd, ssl, stats, storage, strace, stronswan, su, submodules, subzone, sudo, sudoers, sup, swaks, swap, switch, switching, synaptics, synergy, sysfs, systemd, systemtap, tar, tcpdump, tcsh, tee, telnet, terminal, terminator, testdisk, testing, throughput, tmux, todo, tomcat, top, tput, trafficshaping, ttl, tuning, tunnel, tunneling, typo3, uboot, ubuntu, ubuntu 16.04, udev, uefi, ulimit, uname, unetbootin, unit testing, upstart, uptime, usb, usbstick, utf8, utm, utm 220, ux305, vcs, vgchange, vim, vimdiff, virtualbox, virtualization, visual studio code, vlan, vmstat, vmware, vnc, vncviewer, voltage, vpn, vsphere, vzdump, w, w701, wakeonlan, wargames, web, webdav, weechat, wget, whois, wicd, wifi, windowmanager, windows, wine, wireshark, wpa, wpa_passphrase, wpa_supplicant, x11vnc, x2x, xfce, xfreerdp, xmodem, xterm, xxd, yum, zones, zsh


Unless otherwise credited all material Creative Commons License by sjas